Supabase Dart Client - Introduction
Supabase Dart Client - Introduction
dev
Terminal
Initializing
You can initialize Supabase with the static initialize() method of the Supabase class.
The Supabase client is your entrypoint to the rest of the Supabase functionality
and is the easiest way to interact with everything we offer within the Supabase ecosystem.
Parameters
The unique Supabase URL which is supplied when you create a new project in your project dashboard.
The unique Supabase Key which is supplied when you create a new project in your project dashboard.
runApp(MyApp());
}
// Get a reference your Supabase client
final supabase = Supabase.instance.client;
Upgrade guide
Although supabase_flutter v2 brings a few breaking changes, for the most part the public API
should be the same with a few minor exceptions.
We have brought numerous updates behind the scenes to make the SDK work more intuitively for
Flutter and Dart developers.
Make sure you are using v2 of the client library in your pubspec.yaml file.
1 supabase_flutter: ^2.0.0
Before After
main.dart
1 await Supabase.initialize(
2 url: supabaseUrl,
3 anonKey: supabaseKey,
4 authFlowType: AuthFlowType.pkce,
5 storageRetryAttempts: 10,
6 realtimeClientOptions: const RealtimeClientOptions(
7 logLevel: RealtimeLogLevel.info,
8 ),
9 );
Auth updates
Before After
1 await supabase.auth.signInWithOAuth(
2 Provider.google,
3 );
Before After
1 await supabase.auth.signInWithApple();
In v1, Supabase.initialize() would await for the session to be refreshed before returning.
This caused delays in the app's launch time, especially when the app is opened in a poor network
environment.
In v2, Supabase.initialize() returns immediately after obtaining the session from the local
storage, which makes the app launch faster.
Because of this, there is no guarantee that the session is valid when the app starts.
If you need to make sure the session is valid, you can access the isExpired getter to check if
the session is valid.
If the session is expired, you can listen to the onAuthStateChange event and wait for a new
tokenRefreshed event to be fired.
Before After
In v2, we have dropped the webview_flutter dependency in v2 to allow you to have full control
over the UI of the OAuth flow.
We now have native support for Google and Apple sign in, so opening an external browser is no
longer needed on iOS.
Because of this update, we no longer need the context parameter, so we have removed the
context parameter from the signInWithOAuth() method.
Before After
PKCE flow, which is a more secure method for obtaining sessions from deep links, is now the
default auth flow for any authentication involving deep links.
Before After
1 await Supabase.initialize(
2 url: 'SUPABASE_URL',
3 anonKey: 'SUPABASE_ANON_KEY',
4 authFlowType: AuthFlowType.implicit, // set to implicit by default
5 );
Auth callback host name parameter removed
Before After
1 await Supabase.initialize(
2 url: 'SUPABASE_URL',
3 anonKey: 'SUPABASE_ANON_KEY',
4 authCallbackUrlHostname: 'auth-callback',
5 );
The SupabaseAuth had an initialSession member, which was used to obtain the initial
session upon app start.
This is now removed, and currentSession should be used to access the session at any time.
Before After
1 // Use `initialSession` to obtain the initial session when the app starts.
2 final initialSession = await SupabaseAuth.initialSession;
Data methods
Before After
Because is and in are reserved keywords in Dart, v1 used is_ and in_ as query filter
names.
Users found the underscore confusing, so the query filters are now renamed to isFilter and
inFilter .
Before After
count() on .select() performs the select while also getting the count value, and .count()
directly on .from() performs a head request resulting in only fetching the count value.
Before After
The PostgrestException instance thrown by the API methods has a code property. In v1, the
code property contained the http status code.
In v2, the code property contains the PostgREST error code, which is more useful for
debugging.
Before After
1 try {
2 await supabase.from('countries').select();
3 } on PostgrestException catch (error) {
4 error.code; // Contains http status code
5 }
Realtime methods
Realtime methods contains the biggest breaking changes. Most of these changes are to make the
interface more type safe.
Postgres Changes
Use the new .onPostgresChanges() method to listen to realtime changes in the database.
In v1, filters were not strongly typed because they took a String type. In v2, filter takes an
object. Its properties are strictly typed to catch type errors.
The payload of the callback is now typed as well. In v1 , the payload was returned as dynamic .
It is now returned as a PostgresChangePayload object. The object contains the oldRecord
and newRecord properties for accessing the data before and after the change.
Before After
1 supabase.channel('my_channel').on(
2 RealtimeListenTypes.postgresChanges,
3 ChannelFilter(
4 event: '*',
5 schema: 'public',
6 table: 'messages'
6 table: messages ,
7 filter: 'room_id=eq.200',
8 ),
9 (dynamic payload, [ref]) {
10 final Map<String, dynamic> newRecord = payload['new'];
11 final Map<String, dynamic> oldRecord = payload['old'];
12 },
13 ).subscribe();
Broadcast
Broadcast now uses the dedicated .onBroadcast() method, rather than the generic .on()
method.
Because the method is specific to broadcast, it takes fewer properties.
Before After
1 supabase.channel('my_channel').on(
2 RealtimeListenTypes.broadcast,
3 ChannelFilter(
4 event: 'position',
5 ),
6 (dynamic payload, [ref]) {
7 print(payload);
8 },
9 ).subscribe();
Presence
Realtime Presence gets three different methods for listening to three different presence events:
sync , join , and leave .
This allows the callback to be strictly typed.
Before After
1 final channel = supabase.channel('room1');
2
3 channel.on(
4 RealtimeListenTypes.presence,
5 ChannelFilter(event: 'sync'),
6 (payload, [ref]) {
7 print('Synced presence state: ${channel.presenceState()}');
8 },
9 ).on(
10 RealtimeListenTypes.presence,
11 ChannelFilter(event: 'join'),
12 (payload, [ref]) {
13 print('Newly joined presences $payload');
14 },
15 ).on(
16 RealtimeListenTypes.presence,
17 ChannelFilter(event: 'leave'),
18 (payload, [ref]) {
19 print('Newly left presences: $payload');
20 },
21 ).subscribe(
22 (status, [error]) async {
23 if (status == 'SUBSCRIBED') {
24 await channel.track({'online_at': DateTime.now().toIso8601String()});
25 }
26 },
27 );
Fetch data
By default, Supabase projects will return a maximum of 1,000 rows. This setting can be changed in
Project API Settings. It's recommended that you keep it low to limit the payload size of accidental
or malicious requests. You can use range() queries to paginate through your data.
select() can be combined with Filters
apikey is a reserved keyword if you're using the Supabase Platform and should be avoided as a
column name.
Parameters
The columns to retrieve, separated by commas. Columns can be renamed when returned with
customName:columnName
Query referenced tables through a join table Query the same referenced table multiple times
Filtering through referenced tables Querying with count option Querying JSON data
Querying referenced table with inner join Switching schemas per query
Data source
Response
Insert data
Parameters
await supabase
.from('cities')
.insert({'name': 'The Shire', 'country_id': 554});
Data source
Update data
update() should always be combined with Filters to target the item(s) you wish to update.
Parameters
Update your data Update a record and return it Update JSON data
await supabase
.from('countries')
.update({ 'name': 'Australia' })
.eq('id', 1);
Data source
Upsert data
Perform an UPSERT on the table or view. Depending on the column(s) passed to onConflict ,
.upsert() allows you to perform the equivalent of .insert() if a row with the corresponding
onConflict columns doesn't exist, or if it does exist, perform an alternative action depending on
ignoreDuplicates .
Parameters
The values to upsert with. Pass a Map to upsert a single row or an List to upsert multiple rows.
Comma-separated UNIQUE column(s) to specify how duplicate rows are determined. Two rows are duplicates
if all the onConflict columns are equal.
If true, duplicate rows are ignored. If false, duplicate rows are merged with existing rows.
Make missing fields default to null. Otherwise, use the default value for the column. This only applies when
inserting new rows, not when merging with existing rows where ignoreDuplicates is set to false. This also only
applies when doing bulk upserts.
Upsert your data Bulk Upsert your data Upserting into tables with constraints
Data source
Response
Delete data
Perform a DELETE on the table or view.
delete() should always be combined with Filters to target the item(s) you wish to delete.
If you use delete() with filters and you have RLS enabled, only rows visible through SELECT
policies are deleted. Note that by default no rows are visible, so you need at least one
SELECT / ALL policy that makes the rows visible.
await supabase
.from('countries')
.delete()
.eq('id', 1);
Data source
You can call Postgres functions as Remote Procedure Calls, logic in your database that you can
execute from anywhere.
Functions are useful when the logic rarely changes—like for password resets and updates.
Parameters
fn REQUIRED String
Call a Postgres function without arguments Call a Postgres function with arguments Bulk processing
Data source
Response
Using filters
Filters allow you to only return rows that match certain conditions.
If a Database function returns a table response, you can also apply filters.
Applying Filters Chaining Filters Conditional Chaining Filter by values within a JSON column
Notes
Parameters
With `select()`
Data source
Response
Finds all rows whose value on the stated column doesn't match the specified value .
Parameters
column REQUIRED String
With `select()`
Data source
Response
Finds all rows whose value on the stated column is greater than the specified value .
Parameters
With `select()`
Data source
Response
Finds all rows whose value on the stated column is greater than or equal to the specified value .
Parameters
With `select()`
final data = await supabase
.from('countries')
.select()
.gte('id', 2);
Data source
Response
Finds all rows whose value on the stated column is less than the specified value .
Parameters
With `select()`
Response
Finds all rows whose value on the stated column is less than or equal to the specified value .
Parameters
With `select()`
Data source
Response
Column matches a pattern
Finds all rows whose value in the stated column matches the supplied pattern (case sensitive).
Parameters
With `select()`
Data source
Response
Parameters
With `select()`
Data source
Response
Column is a value
A check for exact equality (null, true, false), finds all rows whose value on the stated column exactly
match the specified value .
Parameters
column REQUIRED String
Data source
Response
Notes
Column is in an array
Finds all rows whose value on the stated column is found on the specified values .
Parameters
With `select()`
Data source
Response
Notes
Only relevant for jsonb, array, and range columns. Match only rows where column contains every
element appearing in value .
Parameters
Data source
Response
Notes
Contained by value
Only relevant for jsonb, array, and range columns. Match only rows where every element appearing in
column is contained by value .
Parameters
Data source
Response
Only relevant for range columns. Match only rows where every element in column is greater than
any element in range .
Parameters
With `select()`
Response
Notes
Only relevant for range columns. Match only rows where every element in column is either
contained in range or greater than any element in range .
Parameters
With `select()`
Data source
Response
Notes
Parameters
With `select()`
Data source
Response
Notes
Only relevant for range columns. Match only rows where every element in column is either
contained in range or less than any element in range .
Parameters
With `select()`
Data source
Response
Notes
Only relevant for range columns. Match only rows where column is mutually exclusive to range
and there can be no element between the two ranges.
Parameters
column REQUIRED String
With `select()`
Data source
Response
Notes
Only relevant for array and range columns. Match only rows where column and value have an
element in common.
Parameters
Data source
Response
Match a string
Finds all rows whose tsvector value on the stated column matches to_tsquery(query).
Parameters
Data source
Response
Finds all rows whose columns match the specified query object.
Parameters
The object to filter with, with column names as keys mapped to their filter values
With `select()`
Data source
Response
.not() expects you to use the raw PostgREST syntax for the filter names and values.
1 .not('name','eq','Paris')
Parameters
Data source
Response
.or() expects you to use the raw PostgREST syntax for the filter names and values.
3 .or('id.in.(${mylist.join(',')}),rangecol.cs.(${mylistRange.join(',')}
Parameters
With `select()` Use `or` with `and` Use `or` on referenced tables
Data source
Response
Match only rows which satisfy the filter. This is an escape hatch - you should use the specific filter
methods wherever possible.
.filter() expects you to use the raw PostgREST syntax for the filter names and values, so it
should only be used as an escape hatch in case other filters don't work.
With `select()` With `update()` With `delete()` With `rpc()` On a referenced table
Data source
Response
Using modifiers
Filters work on the row level. That is, they allow you to return rows that
only match certain conditions without changing the shape of the rows.
Modifiers are everything that don't fit that definition—allowing you to
change the format of the response (e.g., returning a CSV string).
Modifiers must be specified after filters. Some modifiers only apply for
queries that return rows (e.g., select() or rpc() on a function that
returns a table response).
With `upsert()`
Data source
Response
Parameters
column REQUIRED String
Data source
Response
Parameters
count REQUIRED int
Set this to limit rows of referenced tables instead of the parent table.
Data source
Response
Parameters
to REQUIRED int
The last index to which to limit the result.
Set this to limit rows of referenced tables instead of the parent table.
With `select()`
Data source
Response
Retrieves only one row from the result. Result must be one row (e.g. using limit), otherwise this will
result in an error.
With `select()`
Data source
Response
With `select()`
Data source
Response
Retrieve as a CSV
Data source
Response
Notes
Using explain
For debugging slow queries, you can get the Postgres EXPLAIN execution plan of a query
using the explain() method. This works on any query, even for rpc() or writes.
Explain is not enabled by default as it can reveal sensitive information about your database.
It's best to only enable this for testing environments but if you wish to enable it for production you
can provide additional protection by using a pre-request function.
Follow the Performance Debugging Guide to enable the functionality on your project.
Parameters
If true, the query will be executed and the actual run time will be returned.
If true, the query identifier will be returned and data will include the output columns of the query.
Get the execution plan Get the execution plan with analyze and verbose
Data source
Response
Notes
Error codes
Supabase Auth can throw or return various errors when using the API. All errors originating from
the supabase.auth namespace of the JavaScript client library will be wrapped by the
AuthError class.
CustomAuthError -- errors which generally originate from state in the client library.
Use the name property on the error to identify the class of error received.
Errors originating from the server API classed as AuthApiError always have a code property
that can be used to identify the error returned by the server. The status property is also
present, encoding the HTTP status code received in the response.
In general the HTTP status codes you will likely receive are:
403 Forbidden is sent out in rare situations where a certain Auth feature is not available for the
user, and you as the developer are not checking a precondition whether that API is available
for the user.
422 Unprocessable Entity is sent out when the API request is accepted, but cannot be
processed because the user or Auth server is in a state where it cannot satisfy the request.
429 Too Many Requests is sent out when rate-limits are breached for an API. You should
handle this status code often, especially in functions that authenticate a user.
500 Internal Server Error often means that the Auth server's service is degraded. Most often it
points to issues in your database setup such as a misbehaving trigger on a schema, function,
view or other database object.
501 Not Implemented is sent out when a feature is not enabled on the Auth server, and you are
trying to use an API which requires it.
To supplement HTTP status codes, Supabase Auth returns a string error code which gives you
more insight into what went wrong. These codes are stable and can be used to present an
internationalized message to your users.
Code Description
bad_code_verifier Returned from the PKCE flow where the provided code verifier
does not match the expected one. Indicates a bug in the
Code Description
bad_json Usually used when the HTTP body of the request is not valid
JSON.
bad_oauth_callback OAuth callback from provider to Auth does not have all the
required attributes (state). Indicates an issue with the OAuth
provider or client library implementation.
email_not_confirmed Signing in is not allowed for this user as the email address is
not confirmed.
flow_state_expired PKCE flow state to which the API request relates has expired.
Ask the user to sign in again.
flow_state_not_found PKCE flow state to which the API request relates no longer
exists. Flow states expire after a while and are progressively
Code Description
cleaned up, which can cause this error. Retried requests can
cause this error, as the previous request likely destroyed the
flow state. Ask the user to sign in again.
identity_already_exists The identity to which the API relates is already linked to a user.
identity_not_found Identity to which the API call relates does not exist, such as
when an identity is unlinked or deleted.
insufficient_aal To call this API, the user must have a higher Authenticator
Assurance Level. To resolve, ask the user to solve an MFA
challenge.
mfa_factor_name_conflict MFA factors for a single user should not have the same friendly
name.
mfa_ip_address_mismatch The enrollment process for MFA factors must begin and end
with the same IP address.
not_admin User accessing the API is not admin, i.e. the JWT does not
contain a role claim that identifies them as an admin of the
Auth server.
otp_disabled Sign in with OTPs (magic link, email OTP) is disabled. Check
your sever's configuration.
otp_expired OTP code for this sign-in has expired. Ask the user to sign in
again.
over_email_send_rate_limit Too many emails have been sent to this email address. Ask the
user to wait a while before trying again.
over_request_rate_limit Too many requests have been sent by this client (IP address).
Ask the user to try again in a few minutes. Sometimes can
indicate a bug in your application that mistakenly sends out too
many requests (such as a badly written useEffect React
hook).
over_sms_send_rate_limit Too many SMS messages have been sent to this phone number.
Ask the user to wait a while before trying again.
phone_not_confirmed Signing in is not allowed for this user as the phone number is
not confirmed.
provider_email_needs_verification Not all OAuth providers verify their user's email address.
Supabase Auth requires emails to be verified, so this error is
sent out when a verification email is sent after completing the
OAuth flow.
saml_assertion_no_email SAML assertion (user information) was received after sign in,
but no email address was found in it which is required. Check
the provider's attribute mapping and/or configuration.
saml_assertion_no_user_id SAML assertion (user information) was received after sign in,
but a user ID (called NameID) was not found in it which is
required. Check the SAML identity provider's configuration.
saml_entity_id_mismatch (Admin API.) Updating the SAML metadata for a SAML identity
provider is not possible, as the entity ID in the update does not
match the entity ID in the database. This is equivalent to
creating a new identity provider, and you should do that
instead.
saml_idp_not_found SAML identity provider not found. Most often returned after
IdP-initiated sign-in with an unregistered SAML identity
provider in Supabase Auth.
saml_provider_disabled Using Enterprise SSO with SAML 2.0 is not enabled on the
Auth server.
session_not_found Session to which the API request relates no longer exists. This
can occur if the user has signed out, or the session entry in the
database was deleted in some other way.
single_identity_not_deletable Every user must have at least one identity attached to it, so
deleting (unlinking) an identity is not allowed if it's the only one
for the user.
sso_domain_already_exists (Admin API.) Only one SSO domain can be registered per SSO
identity provider.
too_many_enrolled_mfa_factors A user can only have a fixed number of enrolled MFA factors.
user_sso_managed When a user comes from SSO, certain fields of the user cannot
be updated (like email ).
Do not use string matching on error messages! Always use the name and code properties of
error objects to identify the situation.
Although HTTP status codes generally don't change, they can suddenly change due to bugs,
so avoid relying on them unless absolutely necessary.
By default, the user needs to verify their email address before logging in. To turn this off, disable
Confirm email in your project.
Confirm email determines if users need to confirm their email address after signing up.
When the user confirms their email address, they are redirected to the SITE_URL by default. You
can modify your SITE_URL or add additional redirect URLs in your project.
If signUp() is called for an existing confirmed user:
When both Confirm email and Confirm phone (even when phone provider is disabled) are
enabled in your project, an obfuscated/fake user object is returned.
When either Confirm email or Confirm phone (even when phone provider is disabled) is
disabled, the error message, User already registered is returned.
Parameters
The URL to redirect the user to after they confirm their email address.
Sign up with an email and password Sign up with a phone number and password (SMS)
Response
Listen to auth events
Listen to auth changes Listen to a specific event Unsubscribe from auth subscription
switch (event) {
case AuthChangeEvent.initialSession:
// handle initial session
case AuthChangeEvent.signedIn:
// handle signed in
case AuthChangeEvent.signedOut:
// handle signed out
case AuthChangeEvent.passwordRecovery:
// handle password recovery
case AuthChangeEvent.tokenRefreshed:
// handle token refreshed
case AuthChangeEvent.userUpdated:
// handle user updated
case AuthChangeEvent.userDeleted:
// handle user deleted
case AuthChangeEvent.mfaChallengeVerified:
// handle mfa challenge verified
}
});
Create an anonymous user
Parameters
Create an anonymous user Create an anonymous user with custom user metadata
await supabase.auth.signInAnonymously();
Response
Sign in a user
Parameters
Sign in with email and password Sign in with phone and password
Response
Sign in with ID Token
Allows you to perform native Google and Apple sign in by combining it with google_sign_in or
sign_in_with_apple packages.
Parameters
The provider to perform the sign in with. Currently, OAuthProvider.google and OAuthProvider.apple
are supported.
Access token obtained from the third-party provider. Required for Google sign in.
Raw nonce value used to perform the third-party sign in. Required for Apple sign-in.
import 'package:google_sign_in/google_sign_in.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
const webClientId = '<web client ID that you registered on Google Cloud, for examp
const iosClientId = '<iOS client ID that you registered on Google Cloud, for examp
if (accessToken == null) {
throw 'No Access Token found.';
}
if (idToken == null) {
throw 'No ID Token found.';
}
Response
Notes
The URL to redirect the user to after they click on the magic link.
If set to false, this method will not create a new user. Defaults to true.
Sign in with email. Sign in with SMS OTP. Sign in with WhatsApp OTP
await supabase.auth.signInWithOtp(
email: '[email protected]',
emailRedirectTo: kIsWeb ? null : 'io.supabase.flutter://signin-callback/',
);
Response
Notes
Parameters
The URL to redirect the user to after they sign in with the third-party provider.
await supabase.auth.signInWithOAuth(OAuthProvider.github);
Before you can call this method you need to establish a connection to an identity provider. Use the
CLI commands to do this.
If you've associated an email domain to the identity provider, you can use the domain property
to start a sign-in flow.
In case you need to use a different way to start the authentication flow with an identity provider,
you can use the providerId property. For example:
Parameters
The URL to redirect the user to after they sign in with the third-party provider.
await supabase.auth.signInWithSSO(
domain: 'company.com',
);
In order to use the signOut() method, the user needs to be signed in first.
Parameters
Whether to sign out from all devices or just the current device. Defaults to SignOutScope.local.
Sign out
await supabase.auth.signOut();
The verifyOtp method takes in different verification types. If a phone number is used, the type
can either be sms or phone_change . If an email address is used, the type can be one of the
following: signup , magiclink , recovery , invite or email_change .
The verification type used should be determined based on the corresponding auth method called
before verifyOtp to sign up or sign in a user.
Parameters
The token that user was sent to their email or mobile phone
Verify Signup One-Time Password (OTP) Verify SMS One-Time Password (OTP)
Response
Retrieve a session
Response
This method will refresh and return a new session whether the current one is expired or not.
Response
Retrieve a user
Response
Update a user
In order to use the updateUser() method, the user needs to be signed in first.
By default, email updates sends a confirmation link to both the user's current and new email. To
only send a confirmation link to the user's new email, disable Secure email change in your
project's email auth provider settings.
Parameters
Update the email for an authenticated user Update the password for an authenticated user
Update the user's metadata Update the user's password with a nonce
Response
Notes
Links an oauth identity to an existing user. This method supports the PKCE flow.
The Enable Manual Linking option must be enabled from your project's authentication settings.
The user needs to be signed in to call linkIdentity() .
If the candidate identity is already linked to the existing user or another user, linkIdentity()
will fail.
Parameters
The URL to redirect the user to after they sign in with the third-party provider.
await supabase.auth.linkIdentity(OAuthProvider.google);
Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that
identity once it's unlinked.
The Enable Manual Linking option must be enabled from your project's authentication settings.
The user needs to be signed in to call unlinkIdentity() .
The user must have at least 2 identities in order to unlink an identity.
The identity to be unlinked must belong to the user.
Parameters
Unlink an identity
This method is used together with updateUser() when a user's password needs to be updated.
This method sends a nonce to the user's email. If the user doesn't have a confirmed email address,
the method sends the nonce to the user's confirmed phone number instead.
await supabase.auth.reauthenticate();
Notes
Resend an OTP
Resends a signup confirmation, email change, or phone change email to the user.
Passwordless sign-ins can be resent by calling the signInWithOtp() method again.
Password recovery emails can be resent by calling the resetPasswordForEmail() method
again.
This method only resend an email or phone OTP to the user if an initial signup, email change, or
phone change request was made.
Resend an email signup confirmation
Notes
The refresh token can only be used once to obtain a new session.
Refresh token rotation is enabled by default on all projects to guard against replay attacks.
You can configure the REFRESH_TOKEN_REUSE_INTERVAL which provides a short window in which
the same refresh token can be used multiple times in the event of concurrency or offline issues.
Parameters
Response
Notes
Auth MFA
This section contains methods commonly used for Multi-Factor Authentication (MFA) and are invoked
behind the supabase.auth.mfa namespace.
Currently, we only support time-based one-time password (TOTP) as the 2nd factor. We don't support
recovery codes but we allow users to enroll more than 1 TOTP factor, with an upper limit of 10.
Having a 2nd TOTP factor for recovery means the user doesn't have to store their recovery codes. It
also reduces the attack surface since the recovery factor is usually time-limited and not a single static
code.
Learn more about implementing MFA on your application on our guide here.
Enroll a factor
Starts the enrollment process for a new Multi-Factor Authentication (MFA) factor. This method
creates a new unverified factor.
To verify a factor, present the QR code or secret to the user and ask them to add it to their
authenticator app.
The user has to enter the code from their authenticator app to verify it.
Currently, totp is the only supported factorType . The returned id should be used to
create a challenge.
To create a challenge, see mfa.challenge() .
To verify a challenge, see mfa.verify() .
To create and verify a challenge in a single step, see mfa.challengeAndVerify() .
Parameters
Response
Create a challenge
Prepares a challenge used to verify that a user has access to a MFA factor.
An enrolled factor is required before creating a challenge.
To verify a challenge, see mfa.verify() .
Parameters
Response
Verify a challenge
Verifies a code against a challenge. The verification code is provided by the user by entering a code
seen in their authenticator app.
Parameters
Response
Helper method which creates a challenge and immediately uses the given code to verify against it
thereafter. The verification code is provided by the user by entering a code seen in their authenticator
app.
Parameters
Response
Unenroll a factor
Parameters
Unenroll a factor
final res = await supabase.auth.mfa.unenroll(
'34e770dd-9ff9-416c-87fa-43b31d7ef225',
);
Response
Returns the Authenticator Assurance Level (AAL) for the active session.
Response
Auth Admin
Retrieve a user
Fetches the user object from the database based on the user's id.
The getUserById() method requires the user's id which maps to the auth.users.id column.
Parameters
Response
Parameters
Response
Create a user
To confirm the user's email address or phone number, set email_confirm or phone_confirm
to true. Both arguments default to false.
createUser() will not send a confirmation email to the user. You can use
inviteUserByEmail() if you want to send them an email invite instead.
If you are sure that the created user's email or phone number is legitimate and verified, you can
set the email_confirm or phone_confirm param to true .
Parameters
With custom user metadata Auto-confirm the user's email Auto-confirm the user's phone number
Response
Delete a user
Delete a user.
The deleteUser() method requires the user's ID, which maps to the auth.users.id column.
Parameters
id REQUIRED String
await supabase.auth.admin
.deleteUser('715ed5db-f090-4b8c-a067-640ecee36aa0');
Parameters
URI to redirect the user to after they open the invite link.
A custom data object to store the user's metadata. This maps to the auth.users.user_metadata column.
Invite a user
Response
Generates email links and OTPs to be sent via a custom email provider.
The following types can be passed into generateLink() : signup , magiclink , invite ,
recovery , emailChangeCurrent , emailChangeNew , phoneChange .
generateLink() only generates the email link for email_change_email if the "Secure email
change" setting is enabled under the "Email" provider in your Supabase project.
generateLink() handles the creation of the user for signup , invite and magiclink .
Parameters
URI to redirect the user to after they open the invite link.
Response
Update a user
Parameters
await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
attributes: AdminUserAttributes(
email: '[email protected]',
),
);
Invokes a Supabase Function. See the guide for details on writing Functions.
Parameters
Realtime is disabled by default for new tables. You can turn it on by managing replication.
stream() will emit the initial data as well as any further change on the database as
Stream<List<Map<String, dynamic>>> by combining Postgrest and Realtime.
Takes a list of primary key column names that will be used to update and delete the proper
records within the SDK.
The following filters are available
.eq('column', value) listens to rows where the column equals the value
.neq('column', value) listens to rows where the column does not equal the value
.gt('column', value) listens to rows where the column is greater than the value
.gte('column', value) listens to rows where the column is greater than or equal to the
value
.lt('column', value) listens to rows where the column is less than the value
.lte('column', value) listens to rows where the column is less than or equal to the value
.inFilter('column', [val1, val2, val3]) listens to rows where the column is one of the
values
Listen to a table With filter, order and limit With an IN filter Using `stream()` with `StreamBuilder`
supabase.from('countries')
.stream(primaryKey: ['id'])
.listen((List<Map<String, dynamic>> data) {
// Do something awesome with the data
});
Subscribe to channel
Realtime is disabled by default for new tables. You can turn it on by managing replication.
If you want to receive the "previous" data for updates and deletes, you will need to set REPLICA
IDENTITY to FULL , like this: ALTER TABLE your_table REPLICA IDENTITY FULL;
Listen to database changes Listen to inserts Listen to updates Listen to deletes Listen to multiple events
Listen to row level changes Listen to broadcast messages Listen to presence events
supabase
.channel('public:countries')
.onPostgresChanges(
event: PostgresChangeEvent.all,
schema: 'public',
table: 'countries',
callback: (payload) {
print('Change received: ${payload.toString()}');
})
.subscribe();
Unsubscribe from a channel
Removing a channel is a great way to maintain the performance of your project's Realtime service
as well as your database if you're listening to Postgres changes. Supabase will automatically
handle cleanup 30 seconds after a client is disconnected, but unused channels may cause
degradation as more clients are simultaneously subscribed.
Remove a channel
Removing channels is a great way to maintain the performance of your project's Realtime service
as well as your database if you're listening to Postgres changes. Supabase will automatically
handle cleanup 30 seconds after a client is disconnected, but unused channels may cause
degradation as more clients are simultaneously subscribed.
Create a bucket
Creates a new Storage bucket
Parameters
id REQUIRED String
Create bucket
Response
Retrieve a bucket
Parameters
id REQUIRED String
Get bucket
Response
Response
Update a bucket
Parameters
id REQUIRED String
Response
Delete a bucket
Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. You must first
empty() the bucket.
Parameters
id REQUIRED String
Delete bucket
Response
Empty a bucket
Parameters
id REQUIRED String
Empty bucket
Response
Upload a file
Parameters
The relative file path. Should be of the format folder/subfolder/filename.png. The bucket must already exist
before attempting to update.
Sets the retryAttempts parameter set across the storage client. Defaults to 10.
Pass a RetryController instance and call cancel() to cancel the retry attempts.
Response
Download a file
Downloads a file.
Parameters
The full path and file name of the file to be downloaded. For example folder/image.png.
Response
Parameters
Response
Parameters
The relative file path. Should be of the format folder/subfolder/filename.png. The bucket must already exist
before attempting to update.
Sets the retryAttempts parameter set across the storage client. Defaults to 10.
Pass a RetryController instance and call cancel() to cancel the retry attempts.
Response
The original file path, including the current file name. For example folder/image.png.
The new file path, including the new file name. For example folder/image-new.png.
Move file
Response
Parameters
paths REQUIRED List<String>
A list of files to delete, including the path and file name. For example ['folder/image.png'].
Delete file
Response
Create signed url to download file without requiring permissions. This URL can be valid for a set
number of seconds.
Parameters
The file path, including the file name. For example folder/image.png.
The bucket needs to be set to public, either via updateBucket() or by going to Storage on
supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
Policy permissions required:
Parameters
Response
Contributing
Author Styleguide
Open Source
SupaSquad
Privacy Settings