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:
If you get stuck while working through this guide, refer to the full example on GitHub .
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 new project in the Supabase Dashboard.
Enter your project details.
Wait for the new database to launch.
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.
Dashboard SQL
Go to the SQL Editor page in the Dashboard.
Click User Management Starter .
Click Run .
You can easily pull the database schema down to your local project by running the db pull
command. Read the local development docs for detailed instructions.
_10 supabase link --project-ref <project-id>
_10 # You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
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.
Go to the API Settings page in the Dashboard.
Find your Project URL
, anon
, and service_role
keys on this page.
Let's start building the Flutter app from scratch.
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: ^2.0.0
Run flutter pub get
to install the dependencies.
Now that we have the dependencies installed let's setup deep links.
Setting up deep links is required to bring back the user to the app when they click on the magic link to sign in.
We can setup deep links with just a minor tweak on our Flutter application.
We have to use io.supabase.flutterquickstart
as the scheme. In this example, we will use login-callback
as the host for our deep link, but you can change it to whatever you would like.
First, add io.supabase.flutterquickstart://login-callback/
as a new redirect URL in the Dashboard.
That is it on Supabase's end and the rest are platform specific settings:
iOS Android Web
Edit the ios/Runner/Info.plist
file.
Add CFBundleURLTypes to enable deep linking:
_20 <!-- ... other tags -->
_20 <!-- ... other tags -->
_20 <!-- Add this array for Deep Links -->
_20 <key>CFBundleURLTypes</key>
_20 <key>CFBundleTypeRole</key>
_20 <string>Editor</string>
_20 <key>CFBundleURLSchemes</key>
_20 <string>io.supabase.flutterquickstart</string>
_20 <!-- ... other tags -->
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.
_10 Future<void> main() async {
_10 await Supabase.initialize(
_10 url: 'YOUR_SUPABASE_URL',
_10 anonKey: 'YOUR_SUPABASE_ANON_KEY',
_10 final supabase = Supabase.instance.client;
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
_38 import 'package:flutter/material.dart';
_38 import 'package:supabase_quickstart/main.dart';
_38 class SplashPage extends StatefulWidget {
_38 const SplashPage({super.key});
_38 _SplashPageState createState() => _SplashPageState();
_38 class _SplashPageState extends State<SplashPage> {
_38 Future<void> _redirect() async {
_38 await Future.delayed(Duration.zero);
_38 final session = supabase.auth.currentSession;
_38 if (session != null) {
_38 Navigator.of(context).pushReplacementNamed('/account');
_38 Navigator.of(context).pushReplacementNamed('/login');
_38 Widget build(BuildContext context) {
_38 return const Scaffold(
_38 body: Center(child: CircularProgressIndicator()),
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
_98 import 'package:flutter/foundation.dart';
_98 import 'package:flutter/material.dart';
_98 import 'package:supabase_flutter/supabase_flutter.dart';
_98 import 'package:supabase_quickstart/main.dart';
_98 class LoginPage extends StatefulWidget {
_98 const LoginPage({super.key});
_98 _LoginPageState createState() => _LoginPageState();
_98 class _LoginPageState extends State<LoginPage> {
_98 bool _isLoading = false;
_98 bool _redirecting = false;
_98 late final TextEditingController _emailController = TextEditingController();
_98 late final StreamSubscription<AuthState> _authStateSubscription;
_98 Future<void> _signIn() async {
_98 await supabase.auth.signInWithOtp(
_98 email: _emailController.text.trim(),
_98 kIsWeb ? null : 'io.supabase.flutterquickstart://login-callback/',
_98 ScaffoldMessenger.of(context).showSnackBar(
_98 const SnackBar(content: Text('Check your email for a login link!')),
_98 _emailController.clear();
_98 } on AuthException catch (error) {
_98 content: Text(error.message),
_98 backgroundColor: Theme.of(context).colorScheme.error,
_98 content: const Text('Unexpected error occurred'),
_98 backgroundColor: Theme.of(context).colorScheme.error,
_98 _authStateSubscription = supabase.auth.onAuthStateChange.listen((data) {
_98 if (_redirecting) return;
_98 final session = data.session;
_98 if (session != null) {
_98 Navigator.of(context).pushReplacementNamed('/account');
_98 _emailController.dispose();
_98 _authStateSubscription.cancel();
_98 Widget build(BuildContext context) {
_98 appBar: AppBar(title: const Text('Sign In')),
_98 padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
_98 const Text('Sign in via the magic link with your email below'),
_98 const SizedBox(height: 18),
_98 controller: _emailController,
_98 decoration: const InputDecoration(labelText: 'Email'),
_98 const SizedBox(height: 18),
_98 onPressed: _isLoading ? null : _signIn,
_98 child: Text(_isLoading ? 'Loading' : 'Send Magic Link'),
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"
_151 import 'package:flutter/material.dart';
_151 import 'package:supabase_flutter/supabase_flutter.dart';
_151 import 'package:supabase_quickstart/main.dart';
_151 class AccountPage extends StatefulWidget {
_151 const AccountPage({super.key});
_151 _AccountPageState createState() => _AccountPageState();
_151 class _AccountPageState extends State<AccountPage> {
_151 final _usernameController = TextEditingController();
_151 final _websiteController = TextEditingController();
_151 var _loading = true;
_151 /// Called once a user id is received within `onAuthenticated()`
_151 Future<void> _getProfile() async {
_151 final userId = supabase.auth.currentUser!.id;
_151 await supabase.from('profiles').select().eq('id', userId).single();
_151 _usernameController.text = (data['username'] ?? '') as String;
_151 _websiteController.text = (data['website'] ?? '') as String;
_151 } on PostgrestException catch (error) {
_151 content: Text(error.message),
_151 backgroundColor: Theme.of(context).colorScheme.error,
_151 content: const Text('Unexpected error occurred'),
_151 backgroundColor: Theme.of(context).colorScheme.error,
_151 /// Called when user taps `Update` button
_151 Future<void> _updateProfile() async {
_151 final userName = _usernameController.text.trim();
_151 final website = _websiteController.text.trim();
_151 final user = supabase.auth.currentUser;
_151 'username': userName,
_151 'updated_at': DateTime.now().toIso8601String(),
_151 await supabase.from('profiles').upsert(updates);
_151 content: Text('Successfully updated profile!'),
_151 } on PostgrestException catch (error) {
_151 content: Text(error.message),
_151 backgroundColor: Theme.of(context).colorScheme.error,
_151 content: const Text('Unexpected error occurred'),
_151 backgroundColor: Theme.of(context).colorScheme.error,
_151 Future<void> _signOut() async {
_151 await supabase.auth.signOut();
_151 } on AuthException catch (error) {
_151 content: Text(error.message),
_151 backgroundColor: Theme.of(context).colorScheme.error,
_151 content: const Text('Unexpected error occurred'),
_151 backgroundColor: Theme.of(context).colorScheme.error,
_151 Navigator.of(context).pushReplacementNamed('/login');
_151 _usernameController.dispose();
_151 _websiteController.dispose();
_151 Widget build(BuildContext context) {
_151 appBar: AppBar(title: const Text('Profile')),
_151 ? const Center(child: CircularProgressIndicator())
_151 padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
_151 controller: _usernameController,
_151 decoration: const InputDecoration(labelText: 'User Name'),
_151 const SizedBox(height: 18),
_151 controller: _websiteController,
_151 decoration: const InputDecoration(labelText: 'Website'),
_151 const SizedBox(height: 18),
_151 onPressed: _loading ? null : _updateProfile,
_151 child: Text(_loading ? 'Saving...' : 'Update'),
_151 const SizedBox(height: 18),
_151 TextButton(onPressed: _signOut, child: const Text('Sign Out')),
Now that we have all the components in place, let's update lib/main.dart
:
_44 import 'package:flutter/material.dart';
_44 import 'package:supabase_flutter/supabase_flutter.dart';
_44 import 'package:supabase_quickstart/pages/account_page.dart';
_44 import 'package:supabase_quickstart/pages/login_page.dart';
_44 import 'package:supabase_quickstart/pages/splash_page.dart';
_44 Future<void> main() async {
_44 await Supabase.initialize(
_44 url: 'YOUR_SUPABASE_URL',
_44 anonKey: 'YOUR_SUPABASE_ANON_KEY',
_44 final supabase = Supabase.instance.client;
_44 class MyApp extends StatelessWidget {
_44 Widget build(BuildContext context) {
_44 title: 'Supabase Flutter',
_44 theme: ThemeData.dark().copyWith(
_44 primaryColor: Colors.green,
_44 textButtonTheme: TextButtonThemeData(
_44 style: TextButton.styleFrom(
_44 foregroundColor: Colors.green,
_44 elevatedButtonTheme: ElevatedButtonThemeData(
_44 style: ElevatedButton.styleFrom(
_44 foregroundColor: Colors.white,
_44 backgroundColor: Colors.green,
_44 routes: <String, WidgetBuilder>{
_44 '/': (_) => const SplashPage(),
_44 '/login': (_) => const LoginPage(),
_44 '/account': (_) => const AccountPage(),
Once that's done, run this in a terminal window to launch on Android or iOS:
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.
Every Supabase project is configured with Storage for managing large files like
photos and videos.
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
:
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.
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
_99 import 'package:flutter/material.dart';
_99 import 'package:image_picker/image_picker.dart';
_99 import 'package:supabase_flutter/supabase_flutter.dart';
_99 import 'package:supabase_quickstart/main.dart';
_99 class Avatar extends StatefulWidget {
_99 required this.imageUrl,
_99 required this.onUpload,
_99 final String? imageUrl;
_99 final void Function(String) onUpload;
_99 _AvatarState createState() => _AvatarState();
_99 class _AvatarState extends State<Avatar> {
_99 bool _isLoading = false;
_99 Widget build(BuildContext context) {
_99 if (widget.imageUrl == null || widget.imageUrl!.isEmpty)
_99 child: Text('No Image'),
_99 onPressed: _isLoading ? null : _upload,
_99 child: const Text('Upload'),
_99 Future<void> _upload() async {
_99 final picker = ImagePicker();
_99 final imageFile = await picker.pickImage(
_99 source: ImageSource.gallery,
_99 if (imageFile == null) {
_99 setState(() => _isLoading = true);
_99 final bytes = await imageFile.readAsBytes();
_99 final fileExt = imageFile.path.split('.').last;
_99 final fileName = '${DateTime.now().toIso8601String()}.$fileExt';
_99 final filePath = fileName;
_99 await supabase.storage.from('avatars').uploadBinary(
_99 fileOptions: FileOptions(contentType: imageFile.mimeType),
_99 final imageUrlResponse = await supabase.storage
_99 .createSignedUrl(filePath, 60 * 60 * 24 * 365 * 10);
_99 widget.onUpload(imageUrlResponse);
_99 } on StorageException catch (error) {
_99 ScaffoldMessenger.of(context).showSnackBar(
_99 content: Text(error.message),
_99 backgroundColor: Theme.of(context).colorScheme.error,
_99 ScaffoldMessenger.of(context).showSnackBar(
_99 content: const Text('Unexpected error occurred'),
_99 backgroundColor: Theme.of(context).colorScheme.error,
_99 setState(() => _isLoading = false);
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
_195 import 'package:flutter/material.dart';
_195 import 'package:supabase_flutter/supabase_flutter.dart';
_195 import 'package:supabase_quickstart/components/avatar.dart';
_195 import 'package:supabase_quickstart/main.dart';
_195 class AccountPage extends StatefulWidget {
_195 const AccountPage({super.key});
_195 _AccountPageState createState() => _AccountPageState();
_195 class _AccountPageState extends State<AccountPage> {
_195 final _usernameController = TextEditingController();
_195 final _websiteController = TextEditingController();
_195 var _loading = true;
_195 /// Called once a user id is received within `onAuthenticated()`
_195 Future<void> _getProfile() async {
_195 final userId = supabase.auth.currentSession!.user.id;
_195 final data = await supabase
_195 _usernameController.text = (data['username'] ?? '') as String;
_195 _websiteController.text = (data['website'] ?? '') as String;
_195 _avatarUrl = (data['avatar_url'] ?? '') as String;
_195 } on PostgrestException catch (error) {
_195 content: Text(error.message),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 content: const Text('Unexpected error occurred'),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 /// Called when user taps `Update` button
_195 Future<void> _updateProfile() async {
_195 final userName = _usernameController.text.trim();
_195 final website = _websiteController.text.trim();
_195 final user = supabase.auth.currentUser;
_195 'username': userName,
_195 'updated_at': DateTime.now().toIso8601String(),
_195 await supabase.from('profiles').upsert(updates);
_195 content: Text('Successfully updated profile!'),
_195 } on PostgrestException catch (error) {
_195 content: Text(error.message),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 content: const Text('Unexpected error occurred'),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 Future<void> _signOut() async {
_195 await supabase.auth.signOut();
_195 } on AuthException catch (error) {
_195 content: Text(error.message),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 content: const Text('Unexpected error occurred'),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 Navigator.of(context).pushReplacementNamed('/login');
_195 /// Called when image has been uploaded to Supabase storage from within Avatar widget
_195 Future<void> _onUpload(String imageUrl) async {
_195 final userId = supabase.auth.currentUser!.id;
_195 await supabase.from('profiles').upsert({
_195 'avatar_url': imageUrl,
_195 content: Text('Updated your profile image!'),
_195 } on PostgrestException catch (error) {
_195 content: Text(error.message),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 content: const Text('Unexpected error occurred'),
_195 backgroundColor: Theme.of(context).colorScheme.error,
_195 _avatarUrl = imageUrl;
_195 _usernameController.dispose();
_195 _websiteController.dispose();
_195 Widget build(BuildContext context) {
_195 appBar: AppBar(title: const Text('Profile')),
_195 ? const Center(child: CircularProgressIndicator())
_195 padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
_195 imageUrl: _avatarUrl,
_195 onUpload: _onUpload,
_195 const SizedBox(height: 18),
_195 controller: _usernameController,
_195 decoration: const InputDecoration(labelText: 'User Name'),
_195 const SizedBox(height: 18),
_195 controller: _websiteController,
_195 decoration: const InputDecoration(labelText: 'Website'),
_195 const SizedBox(height: 18),
_195 onPressed: _loading ? null : _updateProfile,
_195 child: Text(_loading ? 'Saving...' : 'Update'),
_195 const SizedBox(height: 18),
_195 TextButton(onPressed: _signOut, child: const Text('Sign Out')),
Congratulations, you've built a fully functional user management app using Flutter and Supabase!