Quickstart: Flutter

Intro#

This example provides the steps to build a basic user management app. It includes:

  • Supabase Database: a Postgres database for storing your user data.
  • Supabase Auth: users can sign in with magic links (no passwords, only email).
  • Supabase Storage: users can upload a photo.
  • Row Level Security: data is protected so that individuals can only access their own data.
  • Instant APIs: APIs will be automatically generated when you create your database tables.

By the end of this guide you'll have an app which allows users to login and update some basic profile details:

Supabase User Management example

GitHub#

Should you get stuck while working through the guide, refer to this repo.

Project set up#

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. Go to app.supabase.com.
  2. Click on "New Project".
  3. Enter your project details.
  4. 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 URL and anon key from the API settings.

  1. Go to the Settings page in the Dashboard.
  2. Click API in the sidebar.
  3. Find your API 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:

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:

1supabase_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, add an intent-filter to enable deep linking:

android/app/src/main/AndroidManifest.xml
1<manifest ...>
2  <!-- ... other tags -->
3  <application ...>
4    <activity ...>
5      <!-- ... other tags -->
6
7      <!-- Add this intent-filter for Deep Links -->
8      <intent-filter>
9        <action android:name="android.intent.action.VIEW" />
10        <category android:name="android.intent.category.DEFAULT" />
11        <category android:name="android.intent.category.BROWSABLE" />
12        <!-- Accepts URIs that begin with YOUR_SCHEME://YOUR_HOST -->
13        <data
14          android:scheme="io.supabase.flutterquickstart"
15          android:host="login-callback" />
16      </intent-filter>
17
18    </activity>
19  </application>
20</manifest>

For iOS add CFBundleURLTypes to enable deep linking:

ios/Runner/Info.plist"
1<!-- ... other tags -->
2<plist>
3<dict>
4  <!-- ... other tags -->
5
6  <!-- Add this array for Deep Links -->
7  <key>CFBundleURLTypes</key>
8  <array>
9    <dict>
10      <key>CFBundleTypeRole</key>
11      <string>Editor</string>
12      <key>CFBundleURLSchemes</key>
13      <array>
14        <string>io.supabase.flutterquickstart</string>
15      </array>
16    </dict>
17  </array>
18  <!-- ... other tags -->
19</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
1Future<void> main() async {
2  WidgetsFlutterBinding.ensureInitialized();
3
4  await Supabase.initialize(
5    url: 'YOUR_SUPABASE_URL',
6    anonKey: 'YOUR_SUPABASE_ANON_KEY',
7  );
8  runApp(MyApp());
9}

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
1import 'package:flutter/material.dart';
2import 'package:supabase_flutter/supabase_flutter.dart';
3
4final supabase = Supabase.instance.client;
5
6extension ShowSnackBar on BuildContext {
7  void showSnackBar({
8    required String message,
9    Color backgroundColor = Colors.white,
10  }) {
11    ScaffoldMessenger.of(this).showSnackBar(SnackBar(
12      content: Text(message),
13      backgroundColor: backgroundColor,
14    ));
15  }
16
17  void showErrorSnackBar({required String message}) {
18    showSnackBar(message: message, backgroundColor: Colors.red);
19  }
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
1import 'package:flutter/material.dart';
2import 'package:supabase_quickstart/constants.dart';
3
4class SplashPage extends StatefulWidget {
5  const SplashPage({super.key});
6
7  @override
8  _SplashPageState createState() => _SplashPageState();
9}
10
11class _SplashPageState extends State<SplashPage> {
12  bool _redirectCalled = false;
13  @override
14  void didChangeDependencies() {
15    super.didChangeDependencies();
16    _redirect();
17  }
18
19  Future<void> _redirect() async {
20    await Future.delayed(Duration.zero);
21    if (_redirectCalled || !mounted) {
22      return;
23    }
24
25    _redirectCalled = true;
26    final session = supabase.auth.currentSession;
27    if (session != null) {
28      Navigator.of(context).pushReplacementNamed('/account');
29    } else {
30      Navigator.of(context).pushReplacementNamed('/login');
31    }
32  }
33
34  @override
35  Widget build(BuildContext context) {
36    return const Scaffold(
37      body: Center(child: CircularProgressIndicator()),
38    );
39  }
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
1import 'dart:async';
2
3import 'package:flutter/foundation.dart';
4import 'package:flutter/material.dart';
5import 'package:supabase_flutter/supabase_flutter.dart';
6
7import 'package:supabase_quickstart/constants.dart';
8
9class LoginPage extends StatefulWidget {
10  const LoginPage({super.key});
11
12  @override
13  _LoginPageState createState() => _LoginPageState();
14}
15
16class _LoginPageState extends State<LoginPage> {
17  bool _isLoading = false;
18  bool _redirecting = false;
19  late final TextEditingController _emailController;
20  late final StreamSubscription<AuthState> _authStateSubscription;
21
22  Future<void> _signIn() async {
23    setState(() {
24      _isLoading = true;
25    });
26    try {
27      await supabase.auth.signInWithOtp(
28        email: _emailController.text,
29        emailRedirectTo:
30            kIsWeb ? null : 'io.supabase.flutterquickstart://login-callback/',
31      );
32      if (mounted) {
33        context.showSnackBar(message: 'Check your email for login link!');
34        _emailController.clear();
35      }
36    } on AuthException catch (error) {
37      context.showErrorSnackBar(message: error.message);
38    } catch (error) {
39      context.showErrorSnackBar(message: 'Unexpected error occurred');
40    }
41
42    setState(() {
43      _isLoading = false;
44    });
45  }
46
47  @override
48  void initState() {
49    _emailController = TextEditingController();
50    _authStateSubscription = supabase.auth.onAuthStateChange.listen((data) {
51      if (_redirecting) return;
52      final session = data.session;
53      if (session != null) {
54        _redirecting = true;
55        Navigator.of(context).pushReplacementNamed('/account');
56      }
57    });
58    super.initState();
59  }
60
61  @override
62  void dispose() {
63    _emailController.dispose();
64    _authStateSubscription.cancel();
65    super.dispose();
66  }
67
68  @override
69  Widget build(BuildContext context) {
70    return Scaffold(
71      appBar: AppBar(title: const Text('Sign In')),
72      body: ListView(
73        padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
74        children: [
75          const Text('Sign in via the magic link with your email below'),
76          const SizedBox(height: 18),
77          TextFormField(
78            controller: _emailController,
79            decoration: const InputDecoration(labelText: 'Email'),
80          ),
81          const SizedBox(height: 18),
82          ElevatedButton(
83            onPressed: _isLoading ? null : _signIn,
84            child: Text(_isLoading ? 'Loading' : 'Send Magic Link'),
85          ),
86        ],
87      ),
88    );
89  }
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"
1import 'package:flutter/material.dart';
2import 'package:supabase_flutter/supabase_flutter.dart';
3import 'package:supabase_quickstart/components/avatar.dart';
4import 'package:supabase_quickstart/constants.dart';
5
6class AccountPage extends StatefulWidget {
7  const AccountPage({super.key});
8
9  @override
10  _AccountPageState createState() => _AccountPageState();
11}
12
13class _AccountPageState extends State<AccountPage> {
14  final _usernameController = TextEditingController();
15  final _websiteController = TextEditingController();
16  String? _avatarUrl;
17  var _loading = false;
18
19  /// Called once a user id is received within `onAuthenticated()`
20  Future<void> _getProfile() async {
21    setState(() {
22      _loading = true;
23    });
24
25    try {
26      final userId = supabase.auth.currentUser!.id;
27      final data = await supabase
28          .from('profiles')
29          .select()
30          .eq('id', userId)
31          .single() as Map;
32      _usernameController.text = (data['username'] ?? '') as String;
33      _websiteController.text = (data['website'] ?? '') as String;
34      _avatarUrl = (data['avatar_url'] ?? '') as String;
35    } on PostgrestException catch (error) {
36      context.showErrorSnackBar(message: error.message);
37    } catch (error) {
38      context.showErrorSnackBar(message: 'Unexpected exception occurred');
39    }
40
41    setState(() {
42      _loading = false;
43    });
44  }
45
46  /// Called when user taps `Update` button
47  Future<void> _updateProfile() async {
48    setState(() {
49      _loading = true;
50    });
51    final userName = _usernameController.text;
52    final website = _websiteController.text;
53    final user = supabase.auth.currentUser;
54    final updates = {
55      'id': user!.id,
56      'username': userName,
57      'website': website,
58      'updated_at': DateTime.now().toIso8601String(),
59    };
60    try {
61      await supabase.from('profiles').upsert(updates);
62      if (mounted) {
63        context.showSnackBar(message: 'Successfully updated profile!');
64      }
65    } on PostgrestException catch (error) {
66      context.showErrorSnackBar(message: error.message);
67    } catch (error) {
68      context.showErrorSnackBar(message: 'Unexpeted error occurred');
69    }
70    setState(() {
71      _loading = false;
72    });
73  }
74
75  Future<void> _signOut() async {
76    try {
77      await supabase.auth.signOut();
78    } on AuthException catch (error) {
79      context.showErrorSnackBar(message: error.message);
80    } catch (error) {
81      context.showErrorSnackBar(message: 'Unexpected error occurred');
82    }
83    if (mounted) {
84      Navigator.of(context).pushReplacementNamed('/');
85    }
86  }
87
88  @override
89  void initState() {
90    super.initState();
91    _getProfile();
92  }
93
94  @override
95  void dispose() {
96    _usernameController.dispose();
97    _websiteController.dispose();
98    super.dispose();
99  }
100
101  @override
102  Widget build(BuildContext context) {
103    return Scaffold(
104      appBar: AppBar(title: const Text('Profile')),
105      body: ListView(
106        padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
107        children: [
108          TextFormField(
109            controller: _usernameController,
110            decoration: const InputDecoration(labelText: 'User Name'),
111          ),
112          const SizedBox(height: 18),
113          TextFormField(
114            controller: _websiteController,
115            decoration: const InputDecoration(labelText: 'Website'),
116          ),
117          const SizedBox(height: 18),
118          ElevatedButton(
119            onPressed: _updateProfile,
120            child: Text(_loading ? 'Saving...' : 'Update'),
121          ),
122          const SizedBox(height: 18),
123          TextButton(onPressed: _signOut, child: const Text('Sign Out')),
124        ],
125      ),
126    );
127  }
128}

Launch!#

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

lib/main.dart
1import 'package:flutter/material.dart';
2import 'package:supabase_flutter/supabase_flutter.dart';
3import 'package:supabase_quickstart/pages/account_page.dart';
4import 'package:supabase_quickstart/pages/login_page.dart';
5import 'package:supabase_quickstart/pages/splash_page.dart';
6
7Future<void> main() async {
8  await Supabase.initialize(
9    // TODO: Replace credentials with your own
10    url: 'YOUR_SUPABASE_URL',
11    anonKey: 'YOUR_SUPABASE_ANON_KEY',
12  );
13  runApp(MyApp());
14}
15
16class MyApp extends StatelessWidget {
17  @override
18  Widget build(BuildContext context) {
19    return MaterialApp(
20      title: 'Supabase Flutter',
21      theme: ThemeData.dark().copyWith(
22        primaryColor: Colors.green,
23        textButtonTheme: TextButtonThemeData(
24          style: TextButton.styleFrom(
25            foregroundColor: Colors.green,
26          ),
27        ),
28        elevatedButtonTheme: ElevatedButtonThemeData(
29          style: ElevatedButton.styleFrom(
30            foregroundColor: Colors.white,
31            backgroundColor: Colors.green,
32          ),
33        ),
34      ),
35      initialRoute: '/',
36      routes: <String, WidgetBuilder>{
37        '/': (_) => const SplashPage(),
38        '/login': (_) => const LoginPage(),
39        '/account': (_) => const AccountPage(),
40      },
41    );
42  }
43}

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

flutter run

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

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:

1image_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
1import 'package:flutter/material.dart';
2import 'package:image_picker/image_picker.dart';
3import 'package:supabase_flutter/supabase_flutter.dart';
4import 'package:supabase_quickstart/constants.dart';
5
6class Avatar extends StatefulWidget {
7  const Avatar({
8    super.key,
9    required this.imageUrl,
10    required this.onUpload,
11  });
12
13  final String? imageUrl;
14  final void Function(String) onUpload;
15
16  @override
17  _AvatarState createState() => _AvatarState();
18}
19
20class _AvatarState extends State<Avatar> {
21  bool _isLoading = false;
22
23  @override
24  Widget build(BuildContext context) {
25    return Column(
26      children: [
27        if (widget.imageUrl == null || widget.imageUrl!.isEmpty)
28          Container(
29            width: 150,
30            height: 150,
31            color: Colors.grey,
32            child: const Center(
33              child: Text('No Image'),
34            ),
35          )
36        else
37          Image.network(
38            widget.imageUrl!,
39            width: 150,
40            height: 150,
41            fit: BoxFit.cover,
42          ),
43        ElevatedButton(
44          onPressed: _isLoading ? null : _upload,
45          child: const Text('Upload'),
46        ),
47      ],
48    );
49  }
50
51  Future<void> _upload() async {
52    final picker = ImagePicker();
53    final imageFile = await picker.pickImage(
54      source: ImageSource.gallery,
55      maxWidth: 300,
56      maxHeight: 300,
57    );
58    if (imageFile == null) {
59      return;
60    }
61    setState(() => _isLoading = true);
62
63    try {
64      final bytes = await imageFile.readAsBytes();
65      final fileExt = imageFile.path.split('.').last;
66      final fileName = '${DateTime.now().toIso8601String()}.$fileExt';
67      final filePath = fileName;
68      await supabase.storage.from('avatars').uploadBinary(
69            filePath,
70            bytes,
71            fileOptions: FileOptions(contentType: imageFile.mimeType),
72          );
73      final imageUrlResponse = await supabase.storage
74          .from('avatars')
75          .createSignedUrl(filePath, 60 * 60 * 24 * 365 * 10);
76      widget.onUpload(imageUrlResponse);
77    } on StorageException catch (error) {
78      if (mounted) {
79        context.showErrorSnackBar(message: error.message);
80      }
81    } catch (error) {
82      if (mounted) {
83        context.showErrorSnackBar(message: 'Unexpected error occurred');
84      }
85    }
86
87    setState(() => _isLoading = false);
88  }
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
1import 'package:flutter/material.dart';
2import 'package:supabase_flutter/supabase_flutter.dart';
3import 'package:supabase_quickstart/components/avatar.dart';
4import 'package:supabase_quickstart/constants.dart';
5
6class AccountPage extends StatefulWidget {
7  const AccountPage({super.key});
8
9  @override
10  _AccountPageState createState() => _AccountPageState();
11}
12
13class _AccountPageState extends State<AccountPage> {
14  final _usernameController = TextEditingController();
15  final _websiteController = TextEditingController();
16  String? _avatarUrl;
17  var _loading = false;
18
19  /// Called once a user id is received within `onAuthenticated()`
20  Future<void> _getProfile() async {
21    setState(() {
22      _loading = true;
23    });
24
25    try {
26      final userId = supabase.auth.currentUser!.id;
27      final data = await supabase
28          .from('profiles')
29          .select()
30          .eq('id', userId)
31          .single() as Map;
32      _usernameController.text = (data['username'] ?? '') as String;
33      _websiteController.text = (data['website'] ?? '') as String;
34      _avatarUrl = (data['avatar_url'] ?? '') as String;
35    } on PostgrestException catch (error) {
36      context.showErrorSnackBar(message: error.message);
37    } catch (error) {
38      context.showErrorSnackBar(message: 'Unexpected exception occurred');
39    }
40
41    setState(() {
42      _loading = false;
43    });
44  }
45
46  /// Called when user taps `Update` button
47  Future<void> _updateProfile() async {
48    setState(() {
49      _loading = true;
50    });
51    final userName = _usernameController.text;
52    final website = _websiteController.text;
53    final user = supabase.auth.currentUser;
54    final updates = {
55      'id': user!.id,
56      'username': userName,
57      'website': website,
58      'updated_at': DateTime.now().toIso8601String(),
59    };
60    try {
61      await supabase.from('profiles').upsert(updates);
62      if (mounted) {
63        context.showSnackBar(message: 'Successfully updated profile!');
64      }
65    } on PostgrestException catch (error) {
66      context.showErrorSnackBar(message: error.message);
67    } catch (error) {
68      context.showErrorSnackBar(message: 'Unexpeted error occurred');
69    }
70    setState(() {
71      _loading = false;
72    });
73  }
74
75  Future<void> _signOut() async {
76    try {
77      await supabase.auth.signOut();
78    } on AuthException catch (error) {
79      context.showErrorSnackBar(message: error.message);
80    } catch (error) {
81      context.showErrorSnackBar(message: 'Unexpected error occurred');
82    }
83    if (mounted) {
84      Navigator.of(context).pushReplacementNamed('/');
85    }
86  }
87
88  /// Called when image has been uploaded to Supabase storage from within Avatar widget
89  Future<void> _onUpload(String imageUrl) async {
90    try {
91      final userId = supabase.auth.currentUser!.id;
92      await supabase.from('profiles').upsert({
93        'id': userId,
94        'avatar_url': imageUrl,
95      });
96      if (mounted) {
97        context.showSnackBar(message: 'Updated your profile image!');
98      }
99    } on PostgrestException catch (error) {
100      context.showErrorSnackBar(message: error.message);
101    } catch (error) {
102      context.showErrorSnackBar(message: 'Unexpected error has occurred');
103    }
104    if (!mounted) {
105      return;
106    }
107
108    setState(() {
109      _avatarUrl = imageUrl;
110    });
111  }
112
113  @override
114  void initState() {
115    super.initState();
116    _getProfile();
117  }
118
119  @override
120  void dispose() {
121    _usernameController.dispose();
122    _websiteController.dispose();
123    super.dispose();
124  }
125
126  @override
127  Widget build(BuildContext context) {
128    return Scaffold(
129      appBar: AppBar(title: const Text('Profile')),
130      body: ListView(
131        padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
132        children: [
133          Avatar(
134            imageUrl: _avatarUrl,
135            onUpload: _onUpload,
136          ),
137          const SizedBox(height: 18),
138          TextFormField(
139            controller: _usernameController,
140            decoration: const InputDecoration(labelText: 'User Name'),
141          ),
142          const SizedBox(height: 18),
143          TextFormField(
144            controller: _websiteController,
145            decoration: const InputDecoration(labelText: 'Website'),
146          ),
147          const SizedBox(height: 18),
148          ElevatedButton(
149            onPressed: _updateProfile,
150            child: Text(_loading ? 'Saving...' : 'Update'),
151          ),
152          const SizedBox(height: 18),
153          TextButton(onPressed: _signOut, child: const Text('Sign Out')),
154        ],
155      ),
156    );
157  }
158}

Congratulations, that is it! You have now built a fully functional user management app using Flutter and Supabase!

See also#