• Stars
    star
    719
  • Rank 62,985 (Top 2 %)
  • Language
    Dart
  • License
    MIT License
  • Created over 3 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Flutter integration for Supabase. This package makes it simple for developers to build secure and scalable products.

Supabase Flutter

Monorepo containing all Supabase libraries for Flutter.

Documentation: https://supabase.com/docs/reference/dart/introduction


Platform Support

Except Linux, all platforms are fully supported. Linux only doesn't support deeplinks, because of our dependency app_links. All other features are supported.

Getting Started

Import the package:

import 'package:supabase_flutter/supabase_flutter.dart';

Initialize Supabase before using it:

import 'package:supabase_flutter/supabase_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Supabase.initialize(
    url: SUPABASE_URL,
    anonKey: SUPABASE_ANON_KEY,
  );

  runApp(MyApp());
}

// It's handy to then extract the Supabase client in a variable for later uses
final supabase = Supabase.instance.client;

authCallbackUrlHostname is optional. It will be used to filter Supabase authentication redirect deeplink. You need to provide this param if you use deeplink for other features on the app.

debug is optional. It's enabled by default if you're running the app in debug mode (flutter run --debug).

Usage example

Authentication

import 'package:supabase_flutter/supabase_flutter.dart';

final supabase = Supabase.instance.client;

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  late final StreamSubscription<AuthState> _authSubscription;
  User? _user;

  @override
  void initState() {
    _authSubscription = supabase.auth.onAuthStateChange.listen((data) {
      final AuthChangeEvent event = data.event;
      final Session? session = data.session;
      setState(() {
        _user = session?.user;
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _authSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        supabase.auth.signInWithOtp(email: '[email protected]');
      },
      child: const Text('Login'),
    );
  }
}

Native Sign in with Apple example

Before you run the code, you need to register your app ID with Apple with the Sign In with Apple capability selected, and add the bundle ID to your Supabase dashboard in Authentication -> Providers -> Apple.

import 'package:supabase_flutter/supabase_flutter.dart';

final supabase = Supabase.instance.client;

return supabase.auth.signInWithApple();

signInWithApple() is only supported on iOS and on macOS. Other platforms can use the signInWithOAuth() method to perform Apple login.

The signInWithApple method is currently experimental and is subject to change. Follow this issue for platform support progress.

Database

import 'package:supabase_flutter/supabase_flutter.dart';

final supabase = Supabase.instance.client;

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  // Persisting the future as local variable to prevent refetching upon rebuilds.
  final Future<dynamic> _future = supabase
      .from('countries')
      .select()
      .order('name', ascending: true);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _future,
      builder: (context, snapshot) {
        // return your widget with the data from snapshot
      },
    );
  }
}

Realtime

Realtime data as Stream

To receive realtime updates, you have to first enable Realtime on from your Supabase console. You can read more here on how to enable it.

Warning
When using stream() with a StreamBuilder, make sure to persist the stream value as a variable in a StatefulWidget instead of directly constructing the stream within your widget tree, which could cause rapid rebuilds that will lead to losing realtime connection.

import 'package:supabase_flutter/supabase_flutter.dart';

final supabase = Supabase.instance.client;

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  // Persisting the future as local variable to prevent refetching upon rebuilds.
  final List<Map<String, dynamic>> _stream = supabase.from('countries').stream(primaryKey: ['id']);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Map<String, dynamic>>>(
      stream: _stream,
      builder: (context, snapshot) {
        // return your widget with the data from snapshot
      },
    );
  }
}

Postgres Changes

You can get notified whenever there is a change in your Supabase tables.

final myChannel = supabase.channel('my_channel');

myChannel.on(
    RealtimeListenTypes.postgresChanges,
    ChannelFilter(
      event: '*',
      schema: 'public',
      table: 'countries',
    ), (payload, [ref]) {
  // Do something fun or interesting when there is an change on the database
}).subscribe();

Broadcast

Broadcast lets you send and receive low latency messages between connected clients by bypassing the database.

final myChannel = supabase.channel('my_channel');

// Subscribe to `cursor-pos` broadcast event
myChannel.on(RealtimeListenTypes.broadcast,
    ChannelFilter(event: 'cursor-pos'), (payload, [ref]) {
  // Do something fun or interesting when there is an change on the database
}).subscribe();

// Send a broadcast message to other connected clients
await myChannel.send(
  type: RealtimeListenTypes.broadcast,
  event: 'cursor-pos',
  payload: {'x': 30, 'y': 50},
);

Presence

Presence let's you easily create "I'm online" feature.

final myChannel = supabase.channel('my_channel');

// Subscribe to presence events
myChannel.on(
    RealtimeListenTypes.presence, ChannelFilter(event: 'sync'),
    (payload, [ref]) {
  final onlineUsers = myChannel.presenceState();
  // handle sync event
}).on(RealtimeListenTypes.presence, ChannelFilter(event: 'join'),
    (payload, [ref]) {
  // New users have joined
}).on(RealtimeListenTypes.presence, ChannelFilter(event: 'leave'),
    (payload, [ref]) {
  // Users have left
}).subscribe(((status, [_]) async {
  if (status == 'SUBSCRIBED') {
    // Send the current user's state upon subscribing
    final status = await myChannel
        .track({'online_at': DateTime.now().toIso8601String()});
  }
}));

Storage

import 'package:supabase_flutter/supabase_flutter.dart';

final supabase = Supabase.instance.client;

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        final file = File('example.txt');
        file.writeAsStringSync('File content');
        supabase.storage
            .from('my_bucket')
            .upload('my/path/to/files/example.txt', file);
      },
      child: const Text('Upload'),
    );
  }
}

Edge Functions

import 'package:supabase_flutter/supabase_flutter.dart';

final client = Supabase.instance.client;

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  // Persisting the future as local variable to prevent refetching upon rebuilds.
  final _future = client.functions.invoke('get_countries');

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _future,
      builder: (context, snapshot) {
        // return your widget with the data from snapshot
      },
    );
  }
}

Authentication Deep Dive

Using this package automatically persists the auth state on local storage. It also helps you handle authentication with deep link from 3rd party service like Google, Github, Twitter...

Email authentication

import 'package:supabase_flutter/supabase_flutter.dart';

Future<void> signIn(String email, String password) async {
  final response = await Supabase.instance.client.auth.signInWithPassword(email: email, password: password);
  final Session? session = response.session;
  final User? user = response.user;
}

signInWithProvider

This method will automatically launch the auth url and open a browser for user to sign in with 3rd party login.

supabase.auth.signInWithOAuth(
  Provider.google,
  redirectTo: 'io.supabase.flutter://reset-callback/',
);

Custom LocalStorage

As default, supabase_flutter uses hive to persist the user session. Encryption is disabled by default, since an unique encryption key is necessary, and we can not define it. To set an encryptionKey, do the following:

Future<void> main() async {
  // set it before initializing
  HiveLocalStorage.encryptionKey = 'my_secure_key';
  await Supabase.initialize(...);
}

Note the key must be the same. There is no check if the encryption key is correct. If it isn't, there may be unexpected behavior. Learn more about encryption in hive.

However you can use any other methods by creating a LocalStorage implementation. For example, we can use flutter_secure_storage plugin to store the user session in a secure storage.

// Define the custom LocalStorage implementation
class SecureLocalStorage extends LocalStorage {
  SecureLocalStorage() : super(
    initialize: () async {},
    hasAccessToken: () {
      const storage = FlutterSecureStorage();
      return storage.containsKey(key: supabasePersistSessionKey);
    }, accessToken: () {
      const storage = FlutterSecureStorage();
      return storage.read(key: supabasePersistSessionKey);
    }, removePersistedSession: () {
      const storage = FlutterSecureStorage();
      return storage.delete(key: supabasePersistSessionKey);
    }, persistSession: (String value) {
      const storage = FlutterSecureStorage();
      return storage.write(key: supabasePersistSessionKey, value: value);
    },
  );
}

// use it when initializing
Supabase.initialize(
  ...
  localStorage: SecureLocalStorage(),
);

You can also use EmptyLocalStorage to disable session persistence:

Supabase.initialize(
  // ...
  localStorage: const EmptyLocalStorage(),
);

*Currently supabase_flutter supports deep links on Android, iOS, Web, MacOS and Windows.

Supabase redirect URLs config

  • Go to your Supabase project Authentication Settings page.
  • You need to enter your app redirect callback on Additional Redirect URLs field.

The redirect callback url should have this format [YOUR_SCHEME]://[YOUR_AUTH_HOSTNAME]

authentication settings page

Supabase 3rd party logins config

Follow the guide https://supabase.io/docs/guides/auth#third-party-logins

For Android

How to setup

Deep Links can have any custom scheme. The downside is that any app can claim a scheme, so make sure yours are as unique as possible, eg. HST0000001://host.com.

<manifest ...>
  <!-- ... other tags -->
  <application ...>
    <activity ...>
      <!-- ... other tags -->

      <!-- 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="[YOUR_SCHEME]"
          android:host="[YOUR_HOST]" />
      </intent-filter>
    </activity>
  </application>
</manifest>

The android:host attribute is optional for Deep Links.

For more info: https://developer.android.com/training/app-links/deep-linking

For iOS

How to setup

Custom URL schemes can have... any custom scheme and there is no host specificity, nor entitlements or a hosted file. The downside is that any app can claim any scheme, so make sure yours is as unique as possible, eg. hst0000001 or myIncrediblyAwesomeScheme.

For Custom URL schemes you need to declare the scheme in ios/Runner/Info.plist (or through Xcode's Target Info editor, under URL Types):

<!-- ... other tags -->
<plist>
<dict>
  <!-- ... other tags -->
  <key>CFBundleURLTypes</key>
  <array>
    <dict>
      <key>CFBundleTypeRole</key>
      <string>Editor</string>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>[YOUR_SCHEME]</string>
      </array>
    </dict>
  </array>
  <!-- ... other tags -->
</dict>
</plist>

This allows for your app to be started from YOUR_SCHEME://ANYTHING links.

For more info: https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app

For Windows

How to setup

Setting up deep links in Windows has few more steps than other platforms. Learn more

Declare this method in <PROJECT_DIR>\windows\runner\win32_window.h

  // Dispatches link if any.
  // This method enables our app to be with a single instance too.
  // This is optional but mandatory if you want to catch further links in same app.
  bool SendAppLinkToInstance(const std::wstring& title);

Add this inclusion at the top of <PROJECT_DIR>\windows\runner\win32_window.cpp

#include "app_links_windows/app_links_windows_plugin.h"

Add this method in <PROJECT_DIR>\windows\runner\win32_window.cpp

bool Win32Window::SendAppLinkToInstance(const std::wstring& title) {
  // Find our exact window
  HWND hwnd = ::FindWindow(kWindowClassName, title.c_str());

  if (hwnd) {
    // Dispatch new link to current window
    SendAppLink(hwnd);

    // (Optional) Restore our window to front in same state
    WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) };
    GetWindowPlacement(hwnd, &place);
    switch(place.showCmd) {
      case SW_SHOWMAXIMIZED:
          ShowWindow(hwnd, SW_SHOWMAXIMIZED);
          break;
      case SW_SHOWMINIMIZED:
          ShowWindow(hwnd, SW_RESTORE);
          break;
      default:
          ShowWindow(hwnd, SW_NORMAL);
          break;
    }
    SetWindowPos(0, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
    SetForegroundWindow(hwnd);
    // END Restore

    // Window has been found, don't create another one.
    return true;
  }

  return false;
}

Add the call to the previous method in CreateAndShow

bool Win32Window::CreateAndShow(const std::wstring& title,
                                const Point& origin,
                                const Size& size) {
if (SendAppLinkToInstance(title)) {
    return false;
}

...

At this point, you can register your own scheme.
On Windows, URL protocols are setup in the Windows registry.

This package won't do it for you.

You can achieve it with url_protocol inside you app.

The most relevant solution is to include those registry modifications into your installer to allow for deregistration.

For Mac OS

How to setup

Add this XML chapter in your macos/Runner/Info.plist inside chapter:

<!-- ... other tags -->
<plist version="1.0">
<dict>
  <!-- ... other tags -->
  <key>CFBundleURLTypes</key>
  <array>
      <dict>
          <key>CFBundleURLName</key>
          <!-- abstract name for this URL type (you can leave it blank) -->
          <string>sample_name</string>
          <key>CFBundleURLSchemes</key>
          <array>
              <!-- your schemes -->
              <string>sample</string>
          </array>
      </dict>
  </array>
  <!-- ... other tags -->
</dict>
</plist>

Contributing

  • Fork the repo on GitHub
  • Clone the project to your own machine
  • Commit changes to your own branch
  • Push your work back up to your fork
  • Submit a Pull request so that we can review your changes and merge

License

This repo is licenced under MIT.

Resources

More Repositories

1

supabase

The open source Firebase alternative. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript
72,511
star
2

realtime

Broadcast, Presence, and Postgres Changes via WebSockets
Elixir
6,756
star
3

supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
TypeScript
3,211
star
4

pg_graphql

GraphQL support for PostgreSQL
Rust
2,888
star
5

supavisor

A cloud-native, multi-tenant Postgres connection pooler.
Elixir
1,731
star
6

supabase-py

Python Client for Supabase. Query Postgres from Flask, Django, FastAPI. Python user authentication, security policies, edge functions, file storage, and realtime data streaming. Good first issue.
Python
1,680
star
7

index_advisor

PostgreSQL Index Advisor
PLpgSQL
1,612
star
8

ui

Supabase UI Library
TypeScript
1,563
star
9

auth

A JWT based API for managing users and issuing JWT tokens
Go
1,484
star
10

postgres

Unmodified Postgres with some useful plugins
Shell
1,366
star
11

cli

Supabase CLI. Manage postgres migrations, run Supabase locally, deploy edge functions. Postgres backups. Generating types from your database schema.
Go
1,042
star
12

postgrest-js

Isomorphic JavaScript client for PostgREST.
TypeScript
1,036
star
13

pg_jsonschema

PostgreSQL extension providing JSON Schema validation
Rust
1,008
star
14

postgres-meta

A RESTful API for managing your Postgres. Fetch tables, add roles, and run queries
TypeScript
912
star
15

auth-helpers

A collection of framework specific Auth utilities for working with Supabase.
TypeScript
905
star
16

storage

S3 compatible object storage service that stores metadata in Postgres
TypeScript
776
star
17

supabase-swift

A Swift client for Supabase
Swift
696
star
18

edge-runtime

A server based on Deno runtime, capable of running JavaScript, TypeScript, and WASM services.
Rust
671
star
19

supa_audit

Generic Table Auditing
PLpgSQL
647
star
20

pg_replicate

Build Postgres replication apps in Rust
Rust
564
star
21

wrappers

Postgres Foreign Data Wrapper development framework in Rust.
Rust
549
star
22

stripe-sync-engine

Sync your Stripe account to you Postgres database.
TypeScript
490
star
23

auth-ui

Pre-built Auth UI for React
TypeScript
405
star
24

supabase-dart

A Dart client for Supabase
Dart
399
star
25

pg_crdt

POC CRDT support in Postgres
Rust
395
star
26

dbdev

Database Package Registry for Postgres
PLpgSQL
368
star
27

auth-js

An isomorphic Javascript library for Supabase Auth.
CSS
357
star
28

realtime-js

An isomorphic Javascript client for Supabase Realtime server.
TypeScript
318
star
29

examples-archive

Supabase Examples Archive
TypeScript
287
star
30

pg_netstat

PostgreSQL extension to monitor database network traffic
Rust
247
star
31

postgrest-py

PostgREST client for Python. This library provides an ORM interface to PostgREST
Python
230
star
32

pg_net

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL
C
223
star
33

vecs

Postgres/pgvector Python Client
Python
219
star
34

grid

A react component to display your Postgresql table data. Used in Supabase Dashboard app.
TypeScript
202
star
35

libcluster_postgres

Postgres strategy for libcluster
Elixir
190
star
36

supabase-grafana

Observability for your Supabase project, using Prometheus/Grafana
Shell
187
star
37

vault

Extension for storing encrypted secrets in the Vault
PLpgSQL
174
star
38

headless-vector-search

Supabase Toolkit to perform vector similarity search on your knowledge base embeddings.
TypeScript
155
star
39

workflows

Elixir
139
star
40

postgrest-dart

Dart client for PostgREST
Dart
136
star
41

realtime-py

A Python Client for Phoenix Channels
Python
130
star
42

storage-js

JS Client library to interact with Supabase Storage
TypeScript
129
star
43

walrus

Applying RLS to PostgreSQL WAL
PLpgSQL
119
star
44

setup-cli

A GitHub action for interacting with your Supabase projects using the CLI.
TypeScript
113
star
45

postgres-deno

A PostgreSQL extension for Deno: run Typescript in PostgreSQL functions and triggers.
107
star
46

embeddings-generator

GitHub Action to generate embeddings from the markdown files in your repository.
TypeScript
87
star
47

realtime-dart

A dart client for Supabase Realtime server.
Dart
84
star
48

splinter

Supabase Postgres Linter: Performance and Security Advisors
PLpgSQL
83
star
49

repository.surf

πŸ„
JavaScript
80
star
50

supabase-ui-web

TypeScript
74
star
51

auth-py

Python client implementation for Supabase Auth
Python
73
star
52

self-hosted-edge-functions-demo

A demo of how to self-host Supabase Edge Functions on Fly.io
TypeScript
72
star
53

ssr

Supabase clients for use in server-side rendering frameworks.
TypeScript
65
star
54

functions-js

TypeScript
62
star
55

supabase-action-example

TypeScript
61
star
56

supautils

PostgreSQL extension that secures a cluster on a cloud environment
C
59
star
57

supabase-admin-api

API to administer the Supabase server (KPS)
Go
51
star
58

nix-postgres

Experimental port of supabase/postgres to Nix
Nix
47
star
59

gotrue-dart

A dart client library for GoTrue.
Dart
46
star
60

benchmarks

SCSS
45
star
61

storage-py

Python
42
star
62

grafana-agent-fly-example

Deploy a Grafana Agent on Fly to scrape Prometheus metrics from Supabase and send them to Grafana Cloud
Shell
36
star
63

functions-relay

API Gateway for Supabase Edge functions
TypeScript
35
star
64

benchmarks-archive

Infrastucture benchmarks
Nix
31
star
65

hibp

Go library for HaveIBeenPwned.org's pwned passwords API.
Go
31
star
66

supabase.ai

iykyk
HTML
27
star
67

terraform-provider-supabase

Go
23
star
68

livebooks

A collection of Elixir Livebooks for Supabase
Dockerfile
21
star
69

storage-dart

Dart client library to interact with Supabase Storage
Dart
21
star
70

orb-sync-engine

TypeScript
12
star
71

functions-py

Python
12
star
72

auth-elements

Components to add Supabase Auth to any application
TypeScript
11
star
73

rfcs

11
star
74

.github

Org-wide default community health files & templates.
10
star
75

scoop-bucket

8
star
76

functions-dart

Dart
8
star
77

test-reports

Repository to store test reports data and host reporting in gh-pages
7
star
78

plug_caisson

An Elixir Plug library for handling compressed requests
Elixir
7
star
79

flyswatter

Deploy a global pinger on Fly
Elixir
6
star
80

tests

TypeScript
4
star
81

mailme

A clone of Netlify's mailme package used in Supabase Auth / GoTrue.
Go
4
star
82

pgextkit

Rust
3
star
83

homebrew-tap

Ruby
3
star
84

fly-preview

TypeScript
3
star
85

shared-types

TypeScript
3
star
86

supa_type

The Missing PostgreSQL Data Types
Nix
3
star
87

test-inspector

Check your test results against the reference run and compare coverage for multiple client libraries
Go
2
star
88

productions

Supabase SynthWave. The best soundtrack to build an app in a weekend and scale to billions.
TypeScript
2
star
89

design-tokens

1
star