Prepare for the PgBouncer and IPv4 deprecations on 26th January 2024

Home

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.


Future<void> main() async {
  await Supabase.initialize(
    url: 'https://xyzcompany.supabase.co',
    anonKey: 'public-anon-key',
  );

  runApp(MyApp());
}

// Get a reference your Supabase client
final supabase = Supabase.instance.client;

Fetch data

Perform a SELECT query on the table or view.

  • 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
  • select() can be combined with Modifiers
  • apikey is a reserved keyword if you're using the Supabase Platform and should be avoided as a column name.

final data = await supabase
  .from('cities')
  .select('name');

Insert data

Perform an INSERT into the table or view.


await supabase
    .from('cities')
    .insert({'name': 'The Shire', 'country_id': 554});

Update data

Perform an UPDATE on the table or view.

  • update() should always be combined with Filters to target the item(s) you wish to update.

await supabase
  .from('cities')
  .update({ 'name': 'Middle Earth' })
  .match({ 'name': 'Auckland' });

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.

  • Primary keys must be included in values to use upsert.

await supabase
  .from('messages')
  .upsert({ 'id': 3, 'message': 'foo', 'username': 'supabot' });

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('cities')
  .delete()
  .match({ 'id': 666 });

Call a Postgres function

Perform a function call.

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.


final data = await supabase
  .rpc('hello_world');

Using filters

Filters allow you to only return rows that match certain conditions.

Filters can be used on select(), update(), upsert(), and delete() queries.

If a Database function returns a table response, you can also apply filters.


final data = await supabase
  .from('cities')
  .select('name, country_id')
  .eq('name', 'The Shire');  // Correct

final data = await supabase
  .from('cities')
  .eq('name', 'The Shire')  // Incorrect
  .select('name, country_id');

Column is equal to a value

Match only rows where column is equal to value.


final data = await supabase
  .from('countries')
  .select()
  .eq('name', 'Albania');

Column is not equal to a value

Finds all rows whose value on the stated column doesn't match the specified value.


final data = await supabase
  .from('countries')
  .select('name, country_id')
  .neq('name', 'Albania');

Column is greater than a value

Finds all rows whose value on the stated column is greater than the specified value.


final data = await supabase
  .from('countries')
  .select()
  .gt('id', 2);

Column is greater than or equal to a value

Finds all rows whose value on the stated column is greater than or equal to the specified value.


final data = await supabase
  .from('countries')
  .select()
  .gte('id', 2);

Column is less than a value

Finds all rows whose value on the stated column is less than the specified value.


final data = await supabase
  .from('countries')
  .select()
  .lt('id', 2);

Column is less than or equal to a value

Finds all rows whose value on the stated column is less than or equal to the specified value.


final data = await supabase
  .from('countries')
  .select()
  .lte('id', 2);

Column matches a pattern

Finds all rows whose value in the stated column matches the supplied pattern (case sensitive).


final data = await supabase
  .from('countries')
  .select()
  .like('name', '%Alba%');

Column matches a case-insensitive pattern

Finds all rows whose value in the stated column matches the supplied pattern (case insensitive).


final data = await supabase
  .from('countries')
  .select()
  .ilike('name', '%alba%');

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.


final data = await supabase
  .from('countries')
  .select()
  .isFilter('name', null);

Column is in an array

Finds all rows whose value on the stated column is found on the specified values.


final data = await supabase
  .from('countries')
  .select()
  .inFilter('name', ['Albania', 'Algeria']);

Column contains every element in a value


final data = await supabase
  .from('issues')
  .select()
  .contains('tags', ['is:open', 'priority:low']);

Contained by value

Only relevant for jsonb, array, and range columns. Match only rows where every element appearing in column is contained by value.


final data = await supabase
  .from('classes')
  .select('name')
  .containedBy('days', ['monday', 'tuesday', 'wednesday', 'friday']);

Greater than a range

Only relevant for range columns. Match only rows where every element in column is greater than any element in range.


final data = await supabase
  .from('reservations')
  .select()
  .rangeGt('during', '[2000-01-02 08:00, 2000-01-02 09:00)');

Greater than or equal to a range

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.


final data = await supabase
  .from('reservations')
  .select()
  .rangeGte('during', '[2000-01-02 08:30, 2000-01-02 09:30)');

Less than a range

Only relevant for range columns. Match only rows where every element in column is less than any element in range.


final data = await supabase
  .from('reservations')
  .select()
  .rangeLt('during', '[2000-01-01 15:00, 2000-01-01 16:00)');

Less than or equal to a range

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.


final data = await supabase
  .from('reservations')
  .select()
  .rangeLte('during', '[2000-01-01 15:00, 2000-01-01 16:00)');

Mutually exclusive to a range

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.


final data = await supabase
  .from('reservations')
  .select()
  .rangeAdjacent('during', '[2000-01-01 12:00, 2000-01-01 13:00)');

With a common element

Only relevant for array and range columns. Match only rows where column and value have an element in common.


final data = await supabase
  .from('issues')
  .select('title')
  .overlaps('tags', ['is:closed', 'severity:high']);

Match a string

Finds all rows whose tsvector value on the stated column matches to_tsquery(query).

Match an associated value

Finds all rows whose columns match the specified query object.


final data = await supabase
  .from('countries')
  .select()
  .match({ 'id': 2, 'name': 'Albania' });

Don't match the filter

Finds all rows which doesn't satisfy the filter.

  • .not() expects you to use the raw PostgREST syntax for the filter names and values.

    1.not('name','eq','Paris')
    2.not('arraycol','cs','{"a","b"}') // Use Postgres array {} for array column and 'cs' for contains.
    3.not('rangecol','cs','(1,2]') // Use Postgres range syntax for range column.
    4.not('id','in','(6,7)')  // Use Postgres list () and 'in' instead of `inFilter`.
    5.not('id','in','(${mylist.join(',')})')  // You can insert a Dart list array.

final data = await supabase
  .from('cities')
  .select('name, country_id')
  .not('name', 'eq', 'Paris');

Match at least one filter

Finds all rows satisfying at least one of the filters.

  • .or() expects you to use the raw PostgREST syntax for the filter names and values.

    1.or('id.in.(6,7),arraycol.cs.{"a","b"}')  // Use Postgres list () and 'in' instead of `inFilter`. Array {} and 'cs' for contains.
    2.or('id.in.(${mylist.join(',')}),arraycol.cs.{${mylistArray.join(',')}}')	// You can insert a Dart list for list or array column.
    3.or('id.in.(${mylist.join(',')}),rangecol.cs.(${mylistRange.join(',')}]')	// You can insert a Dart list for list or range column.

final data = await supabase
  .from('cities')
  .select('name, country_id')
  .or('id.eq.20,id.eq.30');

Match the filter

Finds all rows whose column satisfies the filter.

  • .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.
    1  .filter('arraycol','cs','{"a","b"}') // Use Postgres array {} and 'cs' for contains.
    2  .filter('rangecol','cs','(1,2]') // Use Postgres range syntax for range column.
    3  .filter('id','in','(6,7)')  // Use Postgres list () and 'in' for in_ filter.
    4  .filter('id','cs','{${mylist.join(',')}}')  // You can insert a Dart array list.

final data = await supabase
  .from('cities')
  .select('name, country_id')
  .filter('name', 'in', '("Paris","Tokyo")');

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).

Order the results

Orders the result with the specified column.


final data = await supabase
  .from('cities')
  .select('name, country_id')
  .order('id', ascending: true);

Limit the number of rows returned

Limits the result with the specified count.


final data = await supabase
  .from('cities')
  .select('name, country_id')
  .limit(1);

Limit the query to a range

Limits the result to rows within the specified range, inclusive.


final data = await supabase
  .from('cities')
  .select('name, country_id')
  .range(0,3);

Retrieve one row of data

Retrieves only one row from the result. Result must be one row (e.g. using limit), otherwise this will result in an error.


final data = await supabase
  .from('cities')
  .select('name, country_id')
  .single();

Create a new user

Creates a new user.

  • 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.
    • If Confirm email is enabled, a user is returned but session is null.
    • If Confirm email is disabled, both a user and a session are returned.
  • 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.

final AuthResponse res = await supabase.auth.signUp(
  email: 'example@email.com',
  password: 'example-password',
);
final Session? session = res.session;
final User? user = res.user;

Listen to auth events

Receive a notification every time an auth event happens.

  • Types of auth events: AuthChangeEvent.passwordRecovery, AuthChangeEvent.signedIn, AuthChangeEvent.signedOut, AuthChangeEvent.tokenRefreshed, AuthChangeEvent.userUpdatedand AuthChangeEvent.userDeleted

final authSubscription = supabase.auth.onAuthStateChange.listen((data) {
  final AuthChangeEvent event = data.event;
  final Session? session = data.session;
});

Sign in a user

Log in an existing user using email or phone number with password.

  • Requires either an email and password or a phone number and password.

final AuthResponse res = await supabase.auth.signInWithPassword(
  email: 'example@email.com',
  password: 'example-password',
);
final Session? session = res.session;
final User? user = res.user;

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.


import 'package:google_sign_in/google_sign_in.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

/// Web Client ID that you registered with Google Cloud.
/// This will be used to perform Google sign in on Android.
const webClientId = 'my-web.apps.googleusercontent.com';

/// iOS Client ID that you registered with Google Cloud.
const iosClientId = 'my-ios.apps.googleusercontent.com';

final GoogleSignIn googleSignIn = GoogleSignIn(
  clientId: iosClientId,
  serverClientId: webClientId,
);
final googleUser = await googleSignIn.signIn();
final googleAuth = await googleUser!.authentication;
final accessToken = googleAuth.accessToken;
final idToken = googleAuth.idToken;

if (accessToken == null) {
  throw 'No Access Token found.';
}
if (idToken == null) {
  throw 'No ID Token found.';
}

final response = await supabase.auth.signInWithIdToken(
  provider: OAuthProvider.google,
  idToken: idToken,
  accessToken: accessToken,
);

Sign in a user through OTP

  • Requires either an email or phone number.
  • This method is used for passwordless sign-ins where an OTP is sent to the user's email or phone number.
  • If you're using an email, you can configure whether you want the user to receive a magiclink or an OTP.
  • If you're using phone, you can configure whether you want the user to receive an OTP.
  • The magic link's destination URL is determined by the SITE_URL. You can modify the SITE_URL or add additional redirect urls in your project.

await supabase.auth.signInWithOtp(
  email: 'example@email.com',
  emailRedirectTo: kIsWeb ? null : 'io.supabase.flutter://signin-callback/',
);

Sign in a user through OAuth

Signs the user in using third-party OAuth providers.

  • This method is used for signing in using a third-party provider.
  • Supabase supports many different third-party providers.

await supabase.auth.signInWithOAuth(OAuthProvider.github);

Sign in a user through SSO

  • 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:
    • Mapping specific user email addresses with an identity provider.
    • Using different hints to identify the correct identity provider, like a company-specific page, IP address or other tracking information.

await supabase.auth.signInWithSSO(
  domain: 'company.com',
);

Sign out a user

Signs out the current user, if there is a logged in user.

  • In order to use the signOut() method, the user needs to be signed in first.

await supabase.auth.signOut();

Verify and log in through OTP

  • 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.

final AuthResponse res = await supabase.auth.verifyOTP(
  type: OtpType.sms,
  token: '111111',
  phone: '+13334445555',
);
final Session? session = res.session;
final User? user = res.user;

Retrieve a session

Returns the session data, if there is an active session.


final Session? session = supabase.auth.currentSession;

Retrieve a new session

  • This method will refresh and return a new session whether the current one is expired or not.

final AuthResponse res = await supabase.auth.refreshSession();
final session = res.session;

Retrieve a user

Returns the user data, if there is a logged in user.


final User? user = supabase.auth.currentUser;

Update a user

Updates user data for a logged in 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.

final UserResponse res = await supabase.auth.updateUser(
  UserAttributes(
    email: 'example@email.com',
  ),
);
final User? updatedUser = res.user;

Send a password reauthentication nonce

  • 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();

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.

final ResendResponse res = await supabase.auth.resend(
  type: OtpType.email,
  email: 'email@example.com',
);

Set the session data

  • setSession() takes in a refresh token and uses it to get a new session.
  • 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.

final refreshToken = supabase.currentSession?.refreshToken ?? '';
final AuthResponse response = await supabase.auth.setSession(refreshToken);

final session = res.session;

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().

final res = await supabase.auth.mfa.enroll(factorType: FactorType.totp);

final qrCodeUrl = res.totp.qrCode;

Create a challenge

Prepares a challenge used to verify that a user has access to a MFA factor.


final res = await supabase.auth.mfa.challenge(
  factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
);

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.


final res = await supabase.auth.mfa.verify(
  factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
  challengeId: '4034ae6f-a8ce-4fb5-8ee5-69a5863a7c15',
  code: '123456',
);

Create and verify a challenge

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.


final res = await supabase.auth.mfa.challengeAndVerify(
  factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
  code: '123456',
);

Unenroll a factor

Unenroll removes a MFA factor. A user has to have an aal2 authenticator level in order to unenroll a verified factor.


final res = await supabase.auth.mfa.unenroll(
  '34e770dd-9ff9-416c-87fa-43b31d7ef225',
);

Get Authenticator Assurance Level

Returns the Authenticator Assurance Level (AAL) for the active session.

  • Authenticator Assurance Level (AAL) is the measure of the strength of an authentication mechanism.
  • In Supabase, having an AAL of aal1 means the user has signed in with their first factor, such as email, password, or OAuth sign-in. An AAL of aal2 means the user has also signed in with their second factor, such as a time-based, one-time-password (TOTP).
  • If the user has a verified factor, the nextLevel field returns aal2. Otherwise, it returns aal1.

final res = supabase.auth.mfa.getAuthenticatorAssuranceLevel();
final currentLevel = res.currentLevel;
final nextLevel = res.nextLevel;
final currentAuthenticationMethods = res.currentAuthenticationMethods;

Auth Admin

  • Any method under the supabase.auth.admin namespace requires a service_role key.
  • These methods are considered admin methods and should be called on a trusted server. Never expose your service_role key in the Flutter app.

final supabase = SupabaseClient(supabaseUrl, serviceRoleKey);

Retrieve a user

Get user by id.

  • 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.

final res = await supabase.auth.admin.getUserById(userId);
final user = res.user;

List all users

Get a list of users.

  • Defaults to return 50 users per page.

// Returns the first 50 users.
final List<User> users = await supabase.auth.admin.listUsers();

Create a user

Creates a new 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.

final res = await supabase.auth.admin.createUser(AdminUserAttributes(
  email: 'user@email.com',
  password: 'password',
  userMetadata: {'name': 'Yoda'},
));

Delete a user

Delete a user.

  • The deleteUser() method requires the user's ID, which maps to the auth.users.id column.

await supabase.auth.admin
    .deleteUser('715ed5db-f090-4b8c-a067-640ecee36aa0');

Send an email invite link

Sends an invite link to the user's email address.


final UserResponse res = await supabase.auth.admin
    .inviteUserByEmail('email@example.com');
final User? user = res.user;

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.

Update a user


final UserResponse res = await supabase.auth.admin.updateUserById(
  '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
  attributes: AdminUserAttributes(
    email: 'new@email.com',
  ),
);

Invokes a Supabase Edge Function.

Invokes a Supabase Function. See the guide for details on writing Functions.

  • Requires an Authorization header.
  • Invoke params generally match the Fetch API spec.

final res = await supabase.functions.invoke('hello', body: {'foo': 'baa'});
final data = res.data;

Listen to database changes

Returns real-time data from your table as a Stream.

  • 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

supabase.from('countries')
  .stream(primaryKey: ['id'])
  .listen((List<Map<String, dynamic>> data) {
  // Do something awesome with the data
});

Subscribe to channel

Subscribe to realtime changes in your database.

  • 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;

supabase
    .channel('public:countries')
    .onPostgresChanges(
        event: PostgresChangeEvent.all,
        schema: 'public',
        table: 'countries',
        callback: (payload) {
          print('Change received: ${payload.toString()}');
        })
    .subscribe();

Unsubscribe from a channel

Unsubscribes and removes Realtime channel from Realtime client.

  • 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.

final status = await supabase.removeChannel(channel);

Unsubscribe from all channels

Unsubscribes and removes all Realtime channels from Realtime client.

  • 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.

final statuses = await supabase.removeAllChannels();

Retrieve all channels

Returns all Realtime channels.


final channels = supabase.getChannels();

Create a bucket

Creates a new Storage bucket

  • Policy permissions required:
    • buckets permissions: insert
    • objects permissions: none

final String bucketId = await supabase
  .storage
  .createBucket('avatars');

Retrieve a bucket

Retrieves the details of an existing Storage bucket.

  • Policy permissions required:
    • buckets permissions: select
    • objects permissions: none

final Bucket bucket = await supabase
  .storage
  .getBucket('avatars');

List all buckets

Retrieves the details of all Storage buckets within an existing product.

  • Policy permissions required:
    • buckets permissions: select
    • objects permissions: none

final List<Bucket> buckets = await supabase
  .storage
  .listBuckets();

Update a bucket

Updates a new Storage bucket

  • Policy permissions required:
    • buckets permissions: update
    • objects permissions: none

final res = await supabase
  .storage
  .updateBucket('avatars', const BucketOptions(public: false));

Delete a bucket

Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. You must first empty() the bucket.

  • Policy permissions required:
    • buckets permissions: select and delete
    • objects permissions: none

final String result = await supabase
  .storage
  .deleteBucket('avatars');

Empty a bucket

Removes all objects inside a single bucket.

  • Policy permissions required:
    • buckets permissions: select
    • objects permissions: select and delete

final String result = await supabase
  .storage
  .emptyBucket('avatars');

Upload a file

Uploads a file to an existing bucket.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: insert

final avatarFile = File('path/to/file');
final String path = await supabase.storage.from('avatars').upload(
      'public/avatar1.png',
      avatarFile,
      fileOptions: const FileOptions(cacheControl: '3600', upsert: false),
    );

Download a file

Downloads a file.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: select

final Uint8List file = await supabase
  .storage
  .from('avatars')
  .download('avatar1.png');

List all files in a bucket

Lists all the files within a bucket.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: select

final List<FileObject> objects = await supabase
  .storage
  .from('avatars')
  .list();

Replace an existing file

Replaces an existing file at the specified path with a new one.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: update and select

final avatarFile = File('path/to/local/file');
final String path = await supabase.storage.from('avatars').update(
      'public/avatar1.png',
      avatarFile,
      fileOptions: const FileOptions(cacheControl: '3600', upsert: false),
    );

Move an existing file

Moves an existing file, optionally renaming it at the same time.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: update and select

final String result = await supabase
  .storage
  .from('avatars')
  .move('public/avatar1.png', 'private/avatar2.png');

Delete files in a bucket

Deletes files within the same bucket

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: delete and select

final List<FileObject> objects = await supabase
  .storage
  .from('avatars')
  .remove(['avatar1.png']);

Create a signed URL

Create signed url to download file without requiring permissions. This URL can be valid for a set number of seconds.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: select

final String signedUrl = await supabase
  .storage
  .from('avatars')
  .createSignedUrl('avatar1.png', 60);

Retrieve public URL

Retrieve URLs for assets in public buckets

  • 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:
    • buckets permissions: none
    • objects permissions: none

final String publicUrl = supabase
  .storage
  .from('public-bucket')
  .getPublicUrl('avatar1.png');