Home

Build a User Management App with Flutter

This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:

  • Supabase Database - a Postgres database for storing your user data and Row Level Security so data is protected and users can only access their own information.
  • Supabase Auth - users log in through magic links sent to their email (without having to set up passwords).
  • Supabase Storage - users can upload a profile photo.

Supabase User Management example

note

If you get stuck while working through this guide, refer to the full example on GitHub.

Project setup#

Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase and then creating a "schema" inside the database.

Create a project#

  1. Create a new project in the Supabase Dashboard.
  2. Enter your project details.
  3. Wait for the new database to launch.

Set up the database schema#

Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, or you can just copy/paste the SQL from below and run it yourself.

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter.
  3. Click Run.

Get the API Keys#

Now that you've created some database tables, you are ready to insert data using the auto-generated API. We just need to get the Project URL and anon key from the API settings.

  1. Go to the API Settings page in the Dashboard.
  2. Find your Project URL, anon, and service_role keys on this page.

Building the App#

Let's start building the Flutter app from scratch.

Initialize a Flutter app#

We can use flutter create to initialize an app called supabase_quickstart:


_10
flutter create supabase_quickstart

Then let's install the only additional dependency: supabase_flutter

Copy and paste the following line in your pubspec.yaml to install the package:


_10
supabase_flutter: ^1.0.0

Run flutter pub get to install the dependencies.

Now that we have the dependencies installed let's setup deep links so users who have logged in via magic link or OAuth can come back to the app.

Add io.supabase.flutterquickstart://login-callback/ as a new redirect URL in the Dashboard.

Supabase console deep link setting

That is it on Supabase's end and the rest are platform specific settings:

For Android, edit the android/app/src/main/AndroidManifest.xml file.

Add an intent-filter to enable deep linking:

android/app/src/main/AndroidManifest.xml

_20
<manifest ...>
_20
<!-- ... other tags -->
_20
<application ...>
_20
<activity ...>
_20
<!-- ... other tags -->
_20
_20
<!-- Add this intent-filter for Deep Links -->
_20
<intent-filter>
_20
<action android:name="android.intent.action.VIEW" />
_20
<category android:name="android.intent.category.DEFAULT" />
_20
<category android:name="android.intent.category.BROWSABLE" />
_20
<!-- Accepts URIs that begin with YOUR_SCHEME://YOUR_HOST -->
_20
<data
_20
android:scheme="io.supabase.flutterquickstart"
_20
android:host="login-callback" />
_20
</intent-filter>
_20
_20
</activity>
_20
</application>
_20
</manifest>

For iOS, edit the ios/Runner/Info.plist file.

Add CFBundleURLTypes to enable deep linking:

ios/Runner/Info.plist"

_20
<!-- ... other tags -->
_20
<plist>
_20
<dict>
_20
<!-- ... other tags -->
_20
_20
<!-- Add this array for Deep Links -->
_20
<key>CFBundleURLTypes</key>
_20
<array>
_20
<dict>
_20
<key>CFBundleTypeRole</key>
_20
<string>Editor</string>
_20
<key>CFBundleURLSchemes</key>
_20
<array>
_20
<string>io.supabase.flutterquickstart</string>
_20
</array>
_20
</dict>
_20
</array>
_20
<!-- ... other tags -->
_20
</dict>
_20
</plist>

For web:

There are no additional configurations.

Main function#

Now that we have deep links ready let's initialize the Supabase client inside our main function with the API credentials that you copied earlier. These variables will be exposed on the app, and that's completely fine since we have Row Level Security enabled on our Database.

lib/main.dart

_10
Future<void> main() async {
_10
WidgetsFlutterBinding.ensureInitialized();
_10
_10
await Supabase.initialize(
_10
url: 'YOUR_SUPABASE_URL',
_10
anonKey: 'YOUR_SUPABASE_ANON_KEY',
_10
);
_10
runApp(MyApp());
_10
}

Setting up some constants and handy functions#

Let's also create a constant file to make it easier to use Supabase client. We will also include an extension method declaration to call showSnackBar with one line of code.

lib/constants.dart

_20
import 'package:flutter/material.dart';
_20
import 'package:supabase_flutter/supabase_flutter.dart';
_20
_20
final supabase = Supabase.instance.client;
_20
_20
extension ShowSnackBar on BuildContext {
_20
void showSnackBar({
_20
required String message,
_20
Color backgroundColor = Colors.white,
_20
}) {
_20
ScaffoldMessenger.of(this).showSnackBar(SnackBar(
_20
content: Text(message),
_20
backgroundColor: backgroundColor,
_20
));
_20
}
_20
_20
void showErrorSnackBar({required String message}) {
_20
showSnackBar(message: message, backgroundColor: Colors.red);
_20
}
_20
}

Set up Splash Screen#

Let's create a splash screen that will be shown to users right after they open the app. This screen retrieves the current session and redirects the user accordingly.

lib/pages/splash_page.dart

_40
import 'package:flutter/material.dart';
_40
import 'package:supabase_quickstart/constants.dart';
_40
_40
class SplashPage extends StatefulWidget {
_40
const SplashPage({super.key});
_40
_40
@override
_40
_SplashPageState createState() => _SplashPageState();
_40
}
_40
_40
class _SplashPageState extends State<SplashPage> {
_40
bool _redirectCalled = false;
_40
@override
_40
void didChangeDependencies() {
_40
super.didChangeDependencies();
_40
_redirect();
_40
}
_40
_40
Future<void> _redirect() async {
_40
await Future.delayed(Duration.zero);
_40
if (_redirectCalled || !mounted) {
_40
return;
_40
}
_40
_40
_redirectCalled = true;
_40
final session = supabase.auth.currentSession;
_40
if (session != null) {
_40
Navigator.of(context).pushReplacementNamed('/account');
_40
} else {
_40
Navigator.of(context).pushReplacementNamed('/login');
_40
}
_40
}
_40
_40
@override
_40
Widget build(BuildContext context) {
_40
return const Scaffold(
_40
body: Center(child: CircularProgressIndicator()),
_40
);
_40
}
_40
}

Set up a Login page#

Let's create a Flutter widget to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords. Notice that this page sets up a listener on the user's auth state using onAuthStateChange. A new event will fire when the user comes back to the app by clicking their magic link, which this page can catch and redirect the user accordingly.

lib/pages/login_page.dart

_90
import 'dart:async';
_90
_90
import 'package:flutter/foundation.dart';
_90
import 'package:flutter/material.dart';
_90
import 'package:supabase_flutter/supabase_flutter.dart';
_90
_90
import 'package:supabase_quickstart/constants.dart';
_90
_90
class LoginPage extends StatefulWidget {
_90
const LoginPage({super.key});
_90
_90
@override
_90
_LoginPageState createState() => _LoginPageState();
_90
}
_90
_90
class _LoginPageState extends State<LoginPage> {
_90
bool _isLoading = false;
_90
bool _redirecting = false;
_90
late final TextEditingController _emailController;
_90
late final StreamSubscription<AuthState> _authStateSubscription;
_90
_90
Future<void> _signIn() async {
_90
setState(() {
_90
_isLoading = true;
_90
});
_90
try {
_90
await supabase.auth.signInWithOtp(
_90
email: _emailController.text.trim(),
_90
emailRedirectTo:
_90
kIsWeb ? null : 'io.supabase.flutterquickstart://login-callback/',
_90
);
_90
if (mounted) {
_90
context.showSnackBar(message: 'Check your email for login link!');
_90
_emailController.clear();
_90
}
_90
} on AuthException catch (error) {
_90
context.showErrorSnackBar(message: error.message);
_90
} catch (error) {
_90
context.showErrorSnackBar(message: 'Unexpected error occurred');
_90
}
_90
_90
setState(() {
_90
_isLoading = false;
_90
});
_90
}
_90
_90
@override
_90
void initState() {
_90
_emailController = TextEditingController();
_90
_authStateSubscription = supabase.auth.onAuthStateChange.listen((data) {
_90
if (_redirecting) return;
_90
final session = data.session;
_90
if (session != null) {
_90
_redirecting = true;
_90
Navigator.of(context).pushReplacementNamed('/account');
_90
}
_90
});
_90
super.initState();
_90
}
_90
_90
@override
_90
void dispose() {
_90
_emailController.dispose();
_90
_authStateSubscription.cancel();
_90
super.dispose();
_90
}
_90
_90
@override
_90
Widget build(BuildContext context) {
_90
return Scaffold(
_90
appBar: AppBar(title: const Text('Sign In')),
_90
body: ListView(
_90
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
_90
children: [
_90
const Text('Sign in via the magic link with your email below'),
_90
const SizedBox(height: 18),
_90
TextFormField(
_90
controller: _emailController,
_90
decoration: const InputDecoration(labelText: 'Email'),
_90
),
_90
const SizedBox(height: 18),
_90
ElevatedButton(
_90
onPressed: _isLoading ? null : _signIn,
_90
child: Text(_isLoading ? 'Loading' : 'Send Magic Link'),
_90
),
_90
],
_90
),
_90
);
_90
}
_90
}

Set up Account page#

After a user is signed in we can allow them to edit their profile details and manage their account. Let's create a new widget called account_page.dart for that.

lib/pages/account_page.dart"

_128
import 'package:flutter/material.dart';
_128
import 'package:supabase_flutter/supabase_flutter.dart';
_128
import 'package:supabase_quickstart/components/avatar.dart';
_128
import 'package:supabase_quickstart/constants.dart';
_128
_128
class AccountPage extends StatefulWidget {
_128
const AccountPage({super.key});
_128
_128
@override
_128
_AccountPageState createState() => _AccountPageState();
_128
}
_128
_128
class _AccountPageState extends State<AccountPage> {
_128
final _usernameController = TextEditingController();
_128
final _websiteController = TextEditingController();
_128
String? _avatarUrl;
_128
var _loading = false;
_128
_128
/// Called once a user id is received within `onAuthenticated()`
_128
Future<void> _getProfile() async {
_128
setState(() {
_128
_loading = true;
_128
});
_128
_128
try {
_128
final userId = supabase.auth.currentUser!.id;
_128
final data = await supabase
_128
.from('profiles')
_128
.select()
_128
.eq('id', userId)
_128
.single() as Map;
_128
_usernameController.text = (data['username'] ?? '') as String;
_128
_websiteController.text = (data['website'] ?? '') as String;
_128
_avatarUrl = (data['avatar_url'] ?? '') as String;
_128
} on PostgrestException catch (error) {
_128
context.showErrorSnackBar(message: error.message);
_128
} catch (error) {
_128
context.showErrorSnackBar(message: 'Unexpected exception occurred');
_128
}
_128
_128
setState(() {
_128
_loading = false;
_128
});
_128
}
_128
_128
/// Called when user taps `Update` button
_128
Future<void> _updateProfile() async {
_128
setState(() {
_128
_loading = true;
_128
});
_128
final userName = _usernameController.text.trim();
_128
final website = _websiteController.text.trim();
_128
final user = supabase.auth.currentUser;
_128
final updates = {
_128
'id': user!.id,
_128
'username': userName,
_128
'website': website,
_128
'updated_at': DateTime.now().toIso8601String(),
_128
};
_128
try {
_128
await supabase.from('profiles').upsert(updates);
_128
if (mounted) {
_128
context.showSnackBar(message: 'Successfully updated profile!');
_128
}
_128
} on PostgrestException catch (error) {
_128
context.showErrorSnackBar(message: error.message);
_128
} catch (error) {
_128
context.showErrorSnackBar(message: 'Unexpeted error occurred');
_128
}
_128
setState(() {
_128
_loading = false;
_128
});
_128
}
_128
_128
Future<void> _signOut() async {
_128
try {
_128
await supabase.auth.signOut();
_128
} on AuthException catch (error) {
_128
context.showErrorSnackBar(message: error.message);
_128
} catch (error) {
_128
context.showErrorSnackBar(message: 'Unexpected error occurred');
_128
}
_128
if (mounted) {
_128
Navigator.of(context).pushReplacementNamed('/');
_128
}
_128
}
_128
_128
@override
_128
void initState() {
_128
super.initState();
_128
_getProfile();
_128
}
_128
_128
@override
_128
void dispose() {
_128
_usernameController.dispose();
_128
_websiteController.dispose();
_128
super.dispose();
_128
}
_128
_128
@override
_128
Widget build(BuildContext context) {
_128
return Scaffold(
_128
appBar: AppBar(title: const Text('Profile')),
_128
body: ListView(
_128
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
_128
children: [
_128
TextFormField(
_128
controller: _usernameController,
_128
decoration: const InputDecoration(labelText: 'User Name'),
_128
),
_128
const SizedBox(height: 18),
_128
TextFormField(
_128
controller: _websiteController,
_128
decoration: const InputDecoration(labelText: 'Website'),
_128
),
_128
const SizedBox(height: 18),
_128
ElevatedButton(
_128
onPressed: _updateProfile,
_128
child: Text(_loading ? 'Saving...' : 'Update'),
_128
),
_128
const SizedBox(height: 18),
_128
TextButton(onPressed: _signOut, child: const Text('Sign Out')),
_128
],
_128
),
_128
);
_128
}
_128
}

Launch!#

Now that we have all the components in place, let's update lib/main.dart:

lib/main.dart

_43
import 'package:flutter/material.dart';
_43
import 'package:supabase_flutter/supabase_flutter.dart';
_43
import 'package:supabase_quickstart/pages/account_page.dart';
_43
import 'package:supabase_quickstart/pages/login_page.dart';
_43
import 'package:supabase_quickstart/pages/splash_page.dart';
_43
_43
Future<void> main() async {
_43
await Supabase.initialize(
_43
// TODO: Replace credentials with your own
_43
url: 'YOUR_SUPABASE_URL',
_43
anonKey: 'YOUR_SUPABASE_ANON_KEY',
_43
);
_43
runApp(MyApp());
_43
}
_43
_43
class MyApp extends StatelessWidget {
_43
@override
_43
Widget build(BuildContext context) {
_43
return MaterialApp(
_43
title: 'Supabase Flutter',
_43
theme: ThemeData.dark().copyWith(
_43
primaryColor: Colors.green,
_43
textButtonTheme: TextButtonThemeData(
_43
style: TextButton.styleFrom(
_43
foregroundColor: Colors.green,
_43
),
_43
),
_43
elevatedButtonTheme: ElevatedButtonThemeData(
_43
style: ElevatedButton.styleFrom(
_43
foregroundColor: Colors.white,
_43
backgroundColor: Colors.green,
_43
),
_43
),
_43
),
_43
initialRoute: '/',
_43
routes: <String, WidgetBuilder>{
_43
'/': (_) => const SplashPage(),
_43
'/login': (_) => const LoginPage(),
_43
'/account': (_) => const AccountPage(),
_43
},
_43
);
_43
}
_43
}

Once that's done, run this in a terminal window to launch on Android or iOS:


_10
flutter run

Or for web, run the following command to launch it on localhost:3000


_10
flutter run -d web-server --web-hostname localhost --web-port 3000

And then open the browser to localhost:3000 and you should see the completed app.

Supabase User Management example

Bonus: Profile photos#

Every Supabase project is configured with Storage for managing large files like photos and videos.

Making sure we have a public bucket#

We will be storing the image as a publicly sharable image. Make sure your avatars bucket is set to public, and if it is not, change the publicity by clicking the dot menu that appears when you hover over the bucket name. You should see an orange Public badge next to your bucket name if your bucket is set to public.

Adding image uploading feature to Account page#

We will use image_picker plugin to select an image from the device.

Add the following line in your pubspec.yaml file to install image_picker:


_10
image_picker: ^0.8.4

Using image_picker requires some additional preparation depending on the platform. Follow the instruction on README.md of image_picker on how to set it up for the platform you are using.

Once you are done with all of the above, it is time to dive into coding.

Create an upload widget#

Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:

lib/components/avatar.dart

_89
import 'package:flutter/material.dart';
_89
import 'package:image_picker/image_picker.dart';
_89
import 'package:supabase_flutter/supabase_flutter.dart';
_89
import 'package:supabase_quickstart/constants.dart';
_89
_89
class Avatar extends StatefulWidget {
_89
const Avatar({
_89
super.key,
_89
required this.imageUrl,
_89
required this.onUpload,
_89
});
_89
_89
final String? imageUrl;
_89
final void Function(String) onUpload;
_89
_89
@override
_89
_AvatarState createState() => _AvatarState();
_89
}
_89
_89
class _AvatarState extends State<Avatar> {
_89
bool _isLoading = false;
_89
_89
@override
_89
Widget build(BuildContext context) {
_89
return Column(
_89
children: [
_89
if (widget.imageUrl == null || widget.imageUrl!.isEmpty)
_89
Container(
_89
width: 150,
_89
height: 150,
_89
color: Colors.grey,
_89
child: const Center(
_89
child: Text('No Image'),
_89
),
_89
)
_89
else
_89
Image.network(
_89
widget.imageUrl!,
_89
width: 150,
_89
height: 150,
_89
fit: BoxFit.cover,
_89
),
_89
ElevatedButton(
_89
onPressed: _isLoading ? null : _upload,
_89
child: const Text('Upload'),
_89
),
_89
],
_89
);
_89
}
_89
_89
Future<void> _upload() async {
_89
final picker = ImagePicker();
_89
final imageFile = await picker.pickImage(
_89
source: ImageSource.gallery,
_89
maxWidth: 300,
_89
maxHeight: 300,
_89
);
_89
if (imageFile == null) {
_89
return;
_89
}
_89
setState(() => _isLoading = true);
_89
_89
try {
_89
final bytes = await imageFile.readAsBytes();
_89
final fileExt = imageFile.path.split('.').last;
_89
final fileName = '${DateTime.now().toIso8601String()}.$fileExt';
_89
final filePath = fileName;
_89
await supabase.storage.from('avatars').uploadBinary(
_89
filePath,
_89
bytes,
_89
fileOptions: FileOptions(contentType: imageFile.mimeType),
_89
);
_89
final imageUrlResponse = await supabase.storage
_89
.from('avatars')
_89
.createSignedUrl(filePath, 60 * 60 * 24 * 365 * 10);
_89
widget.onUpload(imageUrlResponse);
_89
} on StorageException catch (error) {
_89
if (mounted) {
_89
context.showErrorSnackBar(message: error.message);
_89
}
_89
} catch (error) {
_89
if (mounted) {
_89
context.showErrorSnackBar(message: 'Unexpected error occurred');
_89
}
_89
}
_89
_89
setState(() => _isLoading = false);
_89
}
_89
}

Add the new widget#

And then we can add the widget to the Account page as well as some logic to update the avatar_url whenever the user uploads a new avatar.

lib/pages/account_page.dart

_158
import 'package:flutter/material.dart';
_158
import 'package:supabase_flutter/supabase_flutter.dart';
_158
import 'package:supabase_quickstart/components/avatar.dart';
_158
import 'package:supabase_quickstart/constants.dart';
_158
_158
class AccountPage extends StatefulWidget {
_158
const AccountPage({super.key});
_158
_158
@override
_158
_AccountPageState createState() => _AccountPageState();
_158
}
_158
_158
class _AccountPageState extends State<AccountPage> {
_158
final _usernameController = TextEditingController();
_158
final _websiteController = TextEditingController();
_158
String? _avatarUrl;
_158
var _loading = false;
_158
_158
/// Called once a user id is received within `onAuthenticated()`
_158
Future<void> _getProfile() async {
_158
setState(() {
_158
_loading = true;
_158
});
_158
_158
try {
_158
final userId = supabase.auth.currentUser!.id;
_158
final data = await supabase
_158
.from('profiles')
_158
.select()
_158
.eq('id', userId)
_158
.single() as Map;
_158
_usernameController.text = (data['username'] ?? '') as String;
_158
_websiteController.text = (data['website'] ?? '') as String;
_158
_avatarUrl = (data['avatar_url'] ?? '') as String;
_158
} on PostgrestException catch (error) {
_158
context.showErrorSnackBar(message: error.message);
_158
} catch (error) {
_158
context.showErrorSnackBar(message: 'Unexpected exception occurred');
_158
}
_158
_158
setState(() {
_158
_loading = false;
_158
});
_158
}
_158
_158
/// Called when user taps `Update` button
_158
Future<void> _updateProfile() async {
_158
setState(() {
_158
_loading = true;
_158
});
_158
final userName = _usernameController.text.trim();
_158
final website = _websiteController.text.trim();
_158
final user = supabase.auth.currentUser;
_158
final updates = {
_158
'id': user!.id,
_158
'username': userName,
_158
'website': website,
_158
'updated_at': DateTime.now().toIso8601String(),
_158
};
_158
try {
_158
await supabase.from('profiles').upsert(updates);
_158
if (mounted) {
_158
context.showSnackBar(message: 'Successfully updated profile!');
_158
}
_158
} on PostgrestException catch (error) {
_158
context.showErrorSnackBar(message: error.message);
_158
} catch (error) {
_158
context.showErrorSnackBar(message: 'Unexpeted error occurred');
_158
}
_158
setState(() {
_158
_loading = false;
_158
});
_158
}
_158
_158
Future<void> _signOut() async {
_158
try {
_158
await supabase.auth.signOut();
_158
} on AuthException catch (error) {
_158
context.showErrorSnackBar(message: error.message);
_158
} catch (error) {
_158
context.showErrorSnackBar(message: 'Unexpected error occurred');
_158
}
_158
if (mounted) {
_158
Navigator.of(context).pushReplacementNamed('/');
_158
}
_158
}
_158
_158
/// Called when image has been uploaded to Supabase storage from within Avatar widget
_158
Future<void> _onUpload(String imageUrl) async {
_158
try {
_158
final userId = supabase.auth.currentUser!.id;
_158
await supabase.from('profiles').upsert({
_158
'id': userId,
_158
'avatar_url': imageUrl,
_158
});
_158
if (mounted) {
_158
context.showSnackBar(message: 'Updated your profile image!');
_158
}
_158
} on PostgrestException catch (error) {
_158
context.showErrorSnackBar(message: error.message);
_158
} catch (error) {
_158
context.showErrorSnackBar(message: 'Unexpected error has occurred');
_158
}
_158
if (!mounted) {
_158
return;
_158
}
_158
_158
setState(() {
_158
_avatarUrl = imageUrl;
_158
});
_158
}
_158
_158
@override
_158
void initState() {
_158
super.initState();
_158
_getProfile();
_158
}
_158
_158
@override
_158
void dispose() {
_158
_usernameController.dispose();
_158
_websiteController.dispose();
_158
super.dispose();
_158
}
_158
_158
@override
_158
Widget build(BuildContext context) {
_158
return Scaffold(
_158
appBar: AppBar(title: const Text('Profile')),
_158
body: ListView(
_158
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
_158
children: [
_158
Avatar(
_158
imageUrl: _avatarUrl,
_158
onUpload: _onUpload,
_158
),
_158
const SizedBox(height: 18),
_158
TextFormField(
_158
controller: _usernameController,
_158
decoration: const InputDecoration(labelText: 'User Name'),
_158
),
_158
const SizedBox(height: 18),
_158
TextFormField(
_158
controller: _websiteController,
_158
decoration: const InputDecoration(labelText: 'Website'),
_158
),
_158
const SizedBox(height: 18),
_158
ElevatedButton(
_158
onPressed: _updateProfile,
_158
child: Text(_loading ? 'Saving...' : 'Update'),
_158
),
_158
const SizedBox(height: 18),
_158
TextButton(onPressed: _signOut, child: const Text('Sign Out')),
_158
],
_158
),
_158
);
_158
}
_158
}

Storage management#

If you upload additional profile photos, they'll accumulate in the avatars bucket because of their random names with only the latest being referenced from public.profiles and the older versions getting orphaned.

To automatically remove obsolete storage objects, extend the database triggers. Note that it is not sufficient to delete the objects from the storage.objects table because that would orphan and leak the actual storage objects in the S3 backend. Instead, invoke the storage API within Postgres via the http extension.

Enable the http extension for the extensions schema in the Dashboard. Then, define the following SQL functions in the SQL Editor to delete storage objects via the API:


_34
create or replace function delete_storage_object(bucket text, object text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
declare
_34
project_url text := '<YOURPROJECTURL>';
_34
service_role_key text := '<YOURSERVICEROLEKEY>'; -- full access needed
_34
url text := project_url||'/storage/v1/object/'||bucket||'/'||object;
_34
begin
_34
select
_34
into status, content
_34
result.status::int, result.content::text
_34
FROM extensions.http((
_34
'DELETE',
_34
url,
_34
ARRAY[extensions.http_header('authorization','Bearer '||service_role_key)],
_34
NULL,
_34
NULL)::extensions.http_request) as result;
_34
end;
_34
$$;
_34
_34
create or replace function delete_avatar(avatar_url text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
begin
_34
select
_34
into status, content
_34
result.status, result.content
_34
from public.delete_storage_object('avatars', avatar_url) as result;
_34
end;
_34
$$;

Next, add a trigger that removes any obsolete avatar whenever the profile is updated or deleted:


_29
create or replace function delete_old_avatar()
_29
returns trigger
_29
language 'plpgsql'
_29
security definer
_29
as $$
_29
declare
_29
status int;
_29
content text;
_29
begin
_29
if coalesce(old.avatar_url, '') <> ''
_29
and (tg_op = 'DELETE' or (old.avatar_url <> new.avatar_url)) then
_29
select
_29
into status, content
_29
result.status, result.content
_29
from public.delete_avatar(old.avatar_url) as result;
_29
if status <> 200 then
_29
raise warning 'Could not delete avatar: % %', status, content;
_29
end if;
_29
end if;
_29
if tg_op = 'DELETE' then
_29
return old;
_29
end if;
_29
return new;
_29
end;
_29
$$;
_29
_29
create trigger before_profile_changes
_29
before update of avatar_url or delete on public.profiles
_29
for each row execute function public.delete_old_avatar();

Finally, delete the public.profile row before a user is deleted. If this step is omitted, you won't be able to delete users without first manually deleting their avatar image.


_14
create or replace function delete_old_profile()
_14
returns trigger
_14
language 'plpgsql'
_14
security definer
_14
as $$
_14
begin
_14
delete from public.profiles where id = old.id;
_14
return old;
_14
end;
_14
$$;
_14
_14
create trigger before_delete_user
_14
before delete on auth.users
_14
for each row execute function public.delete_old_profile();

Congratulations, you've built a fully functional user management app using Flutter and Supabase!

See also#