Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: Finished up with flutter quick start for the most part

dshukertjr0254f0865c90
diff --git a/web/docs/guides/with-flutter.mdx b/web/docs/guides/with-flutter.mdx
index c4749a062ce..b111e7a4356 100644
--- a/web/docs/guides/with-flutter.mdx
+++ b/web/docs/guides/with-flutter.mdx
@@ -71,7 +71,7 @@ values={[
```sh
1. Go to the "SQL" section.
2. Click "User Management Starter".
-4. Click "Run".
+3. Click "Run".
```
<video width="99%" muted playsInline controls="true">
@@ -184,7 +184,73 @@ supabase_flutter: ^0.0.3
Run `flutter pub get` to install the dependencies.
-Now that we have the dependencies installed let's initialize the Supabase client inside our `main` function with the API credentials that you copied [earlier](#get-the-api-keys).
+### Setup deep links
+
+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.
+
+```sh
+1. Go to the "Authentication" section.
+2. Click "Settings" in the sidebar.
+3. Type `io.supabase.flutterquickstart://login-callback/` in the Additional Redirect URLs input field.
+4. Hit save.
+```
+
+![Supabase console deep link setting](/img/deeplink-setting.png)
+
+That is it on Supabase's end and the rest are platform specific settings:
+
+For Android:
+```xml title="android/app/src/main/AndroidManifest.xml"
+<manifest ...>
+ <!-- ... other tags -->
+ <application ...>
+ <activity ...>
+ <!-- ... other tags -->
+
+ <!-- Add this intent-filter for Deep Links -->
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <!-- Accepts URIs that begin with YOUR_SCHEME://YOUR_HOST -->
+ <data
+ android:scheme="io.supabase.flutterquickstart"
+ android:host="login-callback" />
+ </intent-filter>
+
+ </activity>
+ </application>
+</manifest>
+```
+
+For iOS:
+```xml title="ios/Runner/Info.plist"
+<!-- ... other tags -->
+<plist>
+<dict>
+ <!-- ... other tags -->
+
+ <!-- Add this array for Deep Links -->
+ <key>CFBundleURLTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleTypeRole</key>
+ <string>Editor</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>io.supabase.flutterquickstart</string>
+ </array>
+ </dict>
+ </array>
+ <!-- ... other tags -->
+</dict>
+</plist>
+```
+
+For web:
+There are no additional configurations.
+
+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](#get-the-api-keys).
These variables will be exposed on the app, and that's completely fine since we have
[Row Level Security](/docs/guides/auth#row-level-security) enabled on our Database.
@@ -193,364 +259,356 @@ void main() {
WidgetsFlutterBinding.ensureInitialized();
Supabase.initialize(
- url: YOUR_SUPABASE_URL,
- anonKey: YOUR_SUPABASE_ANNON_KEY,
+ url: '[YOUR_SUPABASE_URL]',
+ anonKey: '[YOUR_SUPABASE_ANNON_KEY]',
+ authCallbackUrlHostname: 'login-callback',
);
runApp(MyApp());
}
```
-<!-- And one optional step is to update the CSS file `styles/globals.css` to make the app look nice.
-You can find the full contents of this file [here](https://raw.githubusercontent.com/supabase/supabase/master/examples/react-user-management/src/index.css). -->
+### Set up AuthState
-### Set up a Login widget
+In order to handle deep links for Android and iOS, let's create a class that will do just that.
+`supabase_flutter` plugin comes with `SupabaseAuthState` class where we can inherit from to react to various deep link events.
-Let's create a Flutter widget to manage logins and sign ups.
+```dart title="lib/components/auth_state.dart"
+import 'package:flutter/material.dart';
+import 'package:supabase/supabase.dart';
+import 'package:supabase_flutter/supabase_flutter.dart';
-Let's set up a React component to manage logins and sign ups.
-We'll use Magic Links, so users can sign in with their email without using passwords.
+class AuthState<T extends StatefulWidget> extends SupabaseAuthState<T> {
+ @override
+ void onUnauthenticated() {
+ Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => false);
+ }
-```jsx title="components/Auth.js"
-import { useState } from 'react'
-import { supabase } from '../utils/supabaseClient'
-
-export default function Auth() {
- const [loading, setLoading] = useState(false)
- const [email, setEmail] = useState('')
-
- const handleLogin = async (email) => {
- try {
- setLoading(true)
- const { error } = await supabase.auth.signIn({ email })
- if (error) throw error
- alert('Check your email for the login link!')
- } catch (error) {
- alert(error.error_description || error.message)
- } finally {
- setLoading(false)
- }
+ @override
+ void onAuthenticated(Session session) {
+ Navigator.of(context).pushNamedAndRemoveUntil('/account', (route) => false);
}
- return (
- <div className="row flex flex-center">
- <div className="col-6 form-widget">
- <h1 className="header">Supabase + Next.js</h1>
- <p className="description">Sign in via magic link with your email below</p>
- <div>
- <input
- className="inputField"
- type="email"
- placeholder="Your email"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- />
- </div>
- <div>
- <button
- onClick={(e) => {
- e.preventDefault()
- handleLogin(email)
- }}
- className="button block"
- disabled={loading}
- >
- <span>{loading ? 'Loading' : 'Send magic link'}</span>
- </button>
- </div>
- </div>
- </div>
- )
+ @override
+ void onPasswordRecovery(Session session) {}
+
+ @override
+ void onErrorAuthenticating(String message) {
+ print('Error authenticating $message');
+ }
}
```
-### Account page
+Let's also create a constant file to to make our lives easier.
-After a user is signed in we can allow them to edit their profile details and manage their account.
+```dart title="lib/utils/constants.dart"
+import 'package:supabase_flutter/supabase_flutter.dart';
-Let's create a new component for that called `Account.js`.
+final supabase = Supabase.instance.client;
+```
-```jsx title="components/Account.js"
-import { useState, useEffect } from 'react'
-import { supabase } from '../utils/supabaseClient'
+### SEt up Splash Screen
-export default function Account({ session }) {
- const [loading, setLoading] = useState(true)
- const [username, setUsername] = useState(null)
- const [website, setWebsite] = useState(null)
- const [avatar_url, setAvatarUrl] = useState(null)
+Let's create a splash screen that will be shown to users right after they open the app.
+This splash screen inherits `AuthState` to redirect users to the appropreate pages depending on their authentication state.
- useEffect(() => {
- getProfile()
- }, [session])
+```dart title="lib/pages/splash_page.dart"
+import 'package:flutter/material.dart';
+import 'package:supabase_flutter_guide/components/auth_state.dart';
- async function getProfile() {
- try {
- setLoading(true)
- const user = supabase.auth.user()
+class SplashPage extends StatefulWidget {
+ const SplashPage({Key? key}) : super(key: key);
- let { data, error, status } = await supabase
- .from('profiles')
- .select(`username, website, avatar_url`)
- .eq('id', user.id)
- .single()
+ @override
+ _SplashPageState createState() => _SplashPageState();
+}
- if (error && status !== 406) {
- throw error
- }
-
- if (data) {
- setUsername(data.username)
- setWebsite(data.website)
- setAvatarUrl(data.avatar_url)
- }
- } catch (error) {
- alert(error.message)
- } finally {
- setLoading(false)
- }
+class _SplashPageState extends AuthState<SplashPage> {
+ @override
+ void initState() {
+ recoverSupabaseSession();
+ super.initState();
}
- async function updateProfile({ username, website, avatar_url }) {
- try {
- setLoading(true)
- const user = supabase.auth.user()
-
- const updates = {
- id: user.id,
- username,
- website,
- avatar_url,
- updated_at: new Date(),
- }
-
- let { error } = await supabase.from('profiles').upsert(updates, {
- returning: 'minimal', // Don't return the value after inserting
- })
-
- if (error) {
- throw error
- }
- } catch (error) {
- alert(error.message)
- } finally {
- setLoading(false)
- }
+ @override
+ Widget build(BuildContext context) {
+ return const Scaffold(
+ body: Center(child: CircularProgressIndicator()),
+ );
}
-
- return (
- <div className="form-widget">
- <div>
- <label htmlFor="email">Email</label>
- <input id="email" type="text" value={session.user.email} disabled />
- </div>
- <div>
- <label htmlFor="username">Name</label>
- <input
- id="username"
- type="text"
- value={username || ''}
- onChange={(e) => setUsername(e.target.value)}
- />
- </div>
- <div>
- <label htmlFor="website">Website</label>
- <input
- id="website"
- type="website"
- value={website || ''}
- onChange={(e) => setWebsite(e.target.value)}
- />
- </div>
-
- <div>
- <button
- className="button block primary"
- onClick={() => updateProfile({ username, website, avatar_url })}
- disabled={loading}
- >
- {loading ? 'Loading ...' : 'Update'}
- </button>
- </div>
-
- <div>
- <button className="button block" onClick={() => supabase.auth.signOut()}>
- Sign Out
- </button>
- </div>
- </div>
- )
}
-
```
+### 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.
-### Launch!
+```dart title="lib/pages/login_page.dart"
+import 'package:flutter/material.dart';
+import 'package:supabase_flutter/supabase_flutter.dart';
+import 'package:supabase_flutter_guide/components/auth_state.dart';
+import 'package:supabase/supabase.dart';
+import 'package:supabase_flutter_guide/utils/constants.dart';
-Now that we have all the components in place, let's update `pages/index.js`:
+class LoginPage extends StatefulWidget {
+ const LoginPage({Key? key}) : super(key: key);
-```jsx title="pages/index.js"
-import { useState, useEffect } from 'react'
-import { supabase } from '../utils/supabaseClient'
-import Auth from '../components/Auth'
-import Account from '../components/Account'
+ @override
+ _LoginPageState createState() => _LoginPageState();
+}
-export default function Home() {
- const [session, setSession] = useState(null)
+class _LoginPageState extends AuthState<LoginPage> {
+ bool _isLoading = false;
+ late final TextEditingController _emailController;
+
+ Future<void> _signIn() async {
+ setState(() {
+ _isLoading = true;
+ });
+ final response = await supabase.auth.signIn(
+ email: _emailController.text,
+ options: AuthOptions(
+ redirectTo: 'io.supabase.flutterquickstart://login-callback/'));
+ if (response.error != null) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(response.error!.message),
+ backgroundColor: Colors.red,
+ ));
+ } else {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('Check your email for login link!')));
+ }
+ setState(() {
+ _emailController.clear();
+ _isLoading = false;
+ });
+ }
- useEffect(() => {
- setSession(supabase.auth.session())
+ @override
+ void initState() {
+ _emailController = TextEditingController();
+ super.initState();
+ }
- supabase.auth.onAuthStateChange((_event, session) => {
- setSession(session)
- })
- }, [])
+ @override
+ void dispose() {
+ _emailController.dispose();
+ super.dispose();
+ }
- return (
- <div className="container" style={{ padding: '50px 0 100px 0' }}>
- {!session ? <Auth /> : <Account key={session.user.id} session={session} />}
- </div>
- )
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(title: const Text('Sign In')),
+ body: ListView(
+ padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
+ children: [
+ const Text('Sign in via the magic link with your email below'),
+ const SizedBox(height: 18),
+ TextFormField(
+ controller: _emailController,
+ decoration: const InputDecoration(labelText: 'Email'),
+ ),
+ const SizedBox(height: 18),
+ ElevatedButton(
+ onPressed: _isLoading ? null : _signIn,
+ child: Text(_isLoading ? 'Loading' : 'Send Magic Link'),
+ ),
+ ],
+ ),
+ );
+ }
}
```
-Once that's done, run this in a terminal window:
-
-```bash
-npm run dev
-```
+### Set up Account page
-And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
+After a user is signed in we can allow them to edit their profile details and manage their account.
+Let's create a new component for that called `account_page.dart`.
-![Supabase User demo](/img/supabase-react-demo.png)
+```dart title="lib/pages/account_page.dart"
+import 'package:flutter/material.dart';
+import 'package:supabase_flutter/supabase_flutter.dart';
+import 'package:supabase_flutter_guide/components/auth_state.dart';
+import 'package:supabase_flutter_guide/utils/constants.dart';
-## Bonus: Profile photos
+class AccountPage extends StatefulWidget {
+ const AccountPage({Key? key}) : super(key: key);
-Every Supabase project is configured with [Storage](/docs/guides/storage) for managing large files like
-photos and videos.
+ @override
+ _AccountPageState createState() => _AccountPageState();
+}
-### Create an upload widget
+class _AccountPageState extends AuthState<AccountPage> {
+ late final _usernameController = TextEditingController();
+ late final _websiteController = TextEditingController();
+ var _loading = false;
+
+ Future<void> _getProfile() async {
+ setState(() {
+ _loading = true;
+ });
+ final user = supabase.auth.user()!;
+ final response = await supabase
+ .from('profiles')
+ .select()
+ .eq('id', user.id)
+ .single()
+ .execute();
+ if (response.error != null && response.status != 406) {
+ ScaffoldMessenger.of(context)
+ .showSnackBar(SnackBar(content: Text(response.error!.message)));
+ }
+ if (response.data != null) {
+ _usernameController.text = response.data!['username'] as String;
+ _websiteController.text = response.data!['website'] as String;
+ }
+ setState(() {
+ _loading = false;
+ });
+ }
-Let's create an avatar for the user so that they can upload a profile photo.
-We can start by creating a new component:
+ Future<void> _updateProfile() async {
+ setState(() {
+ _loading = true;
+ });
+ final userName = _usernameController.text;
+ final website = _websiteController.text;
+ final user = supabase.auth.currentUser;
+ final updates = {
+ 'id': user!.id,
+ 'username': userName,
+ 'website': website,
+ 'updated_at': DateTime.now().toIso8601String(),
+ };
+ final response = await supabase.from('profiles').upsert(updates).execute();
+ if (response.error != null) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(response.error!.message),
+ backgroundColor: Colors.red,
+ ));
+ } else {
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('Successfully updated profile!')));
+ }
+ setState(() {
+ _loading = false;
+ });
+ }
-```jsx title="components/Avatar.js"
-import { useEffect, useState } from 'react'
-import { supabase } from '../utils/supabaseClient'
+ Future<void> _signOut() async {
+ final response = await supabase.auth.signOut();
+ if (response.error != null) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text(response.error!.message),
+ backgroundColor: Colors.red,
+ ));
+ }
+ Navigator.of(context).pushReplacementNamed('/login');
+ }
-export default function Avatar({ url, size, onUpload }) {
- const [avatarUrl, setAvatarUrl] = useState(null)
- const [uploading, setUploading] = useState(false)
+ @override
+ void initState() {
+ _getProfile();
+ super.initState();
+ }
- useEffect(() => {
- if (url) downloadImage(url)
- }, [url])
+ @override
+ void dispose() {
+ _usernameController.dispose();
+ _websiteController.dispose();
+ super.dispose();
+ }
- async function downloadImage(path) {
- try {
- const { data, error } = await supabase.storage.from('avatars').download(path)
- if (error) {
- throw error
- }
- const url = URL.createObjectURL(data)
- setAvatarUrl(url)
- } catch (error) {
- console.log('Error downloading image: ', error.message)
- }
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(title: const Text('Profile')),
+ body: ListView(
+ padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
+ children: [
+ TextFormField(
+ controller: _usernameController,
+ decoration: const InputDecoration(labelText: 'User Name'),
+ ),
+ const SizedBox(height: 18),
+ TextFormField(
+ controller: _websiteController,
+ decoration: const InputDecoration(labelText: 'Website'),
+ ),
+ const SizedBox(height: 18),
+ ElevatedButton(
+ onPressed: _updateProfile,
+ child: Text(_loading ? 'Saving...' : 'Update')),
+ const SizedBox(height: 18),
+ ElevatedButton(onPressed: _signOut, child: const Text('Sign Out')),
+ ],
+ ),
+ );
}
+}
+```
- async function uploadAvatar(event) {
- try {
- setUploading(true)
- if (!event.target.files || event.target.files.length === 0) {
- throw new Error('You must select an image to upload.')
- }
+### Launch!
- const file = event.target.files[0]
- const fileExt = file.name.split('.').pop()
- const fileName = `${Math.random()}.${fileExt}`
- const filePath = `${fileName}`
+Now that we have all the components in place, let's update `lib/main.dart`:
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file)
+```dart title="lib/main.dart"
+import 'package:flutter/material.dart';
+import 'package:supabase_flutter/supabase_flutter.dart';
+import 'package:supabase_flutter_guide/pages/account_page.dart';
+import 'package:supabase_flutter_guide/pages/login_page.dart';
+import 'package:supabase_flutter_guide/pages/splash_page.dart';
- if (uploadError) {
- throw uploadError
- }
+void main() {
+ WidgetsFlutterBinding.ensureInitialized();
- onUpload(filePath)
- } catch (error) {
- alert(error.message)
- } finally {
- setUploading(false)
- }
- }
+ Supabase.initialize(
+ url: '[YOUR_SUPABASE_URL]',
+ anonKey: '[YOUR_SUPABASE_ANNON_KEY]',
+ );
+ runApp(MyApp());
+}
- return (
- <div>
- {avatarUrl ? (
- <img
- src={avatarUrl}
- alt="Avatar"
- className="avatar image"
- style={{ height: size, width: size }}
- />
- ) : (
- <div className="avatar no-image" style={{ height: size, width: size }} />
- )}
- <div style={{ width: size }}>
- <label className="button primary block" htmlFor="single">
- {uploading ? 'Uploading ...' : 'Upload'}
- </label>
- <input
- style={{
- visibility: 'hidden',
- position: 'absolute',
- }}
- type="file"
- id="single"
- accept="image/*"
- onChange={uploadAvatar}
- disabled={uploading}
- />
- </div>
- </div>
- )
+class MyApp extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ title: 'Supabase Flutter',
+ theme: ThemeData.dark().copyWith(
+ primaryColor: Colors.green,
+ accentColor: Colors.green,
+ elevatedButtonTheme: ElevatedButtonThemeData(
+ style: ElevatedButton.styleFrom(
+ onPrimary: Colors.white,
+ primary: Colors.green,
+ ),
+ ),
+ ),
+ initialRoute: '/',
+ routes: <String, WidgetBuilder>{
+ '/': (_) => const SplashPage(),
+ '/login': (_) => const LoginPage(),
+ '/account': (_) => const AccountPage(),
+ },
+ );
+ }
}
```
+Once that's done, run this in a terminal window:
-### Add the new widget
-
-And then we can add the widget to the Account page:
-
-
-```jsx title="components/Account.js"
-// Import the new component
-import Avatar from './Avatar'
+```bash
+flutter run
+```
-// ...
+And then open the browser to [localhost:3000](http://localhost:3000) and you should see the completed app.
-return (
- <div className="form-widget">
- {/* Add to the body */}
- <Avatar
- url={avatar_url}
- size={150}
- onUpload={(url) => {
- setAvatarUrl(url)
- updateProfile({ username, website, avatar_url: url })
- }}
- />
- {/* ... */}
- </div>
-)
-```
+![Supabase User demo](/img/supabase-react-demo.png)
## Next steps
diff --git a/web/static/img/deeplink-setting.png b/web/static/img/deeplink-setting.png
new file mode 100644
index 00000000000..ebfa4cce24a
Binary files /dev/null and b/web/static/img/deeplink-setting.png differ