Flutter and Supabase Integration
Supabase, often referred to as an open-source alternative to Firebase, offers a suite of tools including a Postgres database, authentication, real-time subscriptions, and storage. When integrated with Flutter, it allows developers to build sophisticated, scalable, and interactive applications. This article will guide you through the integration of Supabase with Flutter, covering aspects like database operations, authentication, real-time subscriptions, and file storage, along with detailed code examples.
Setting Up Supabase with Flutter
Before diving into the integration, ensure you have Flutter installed. Then, set up a Supabase project:
- Create a Supabase Project: Visit Supabase.io, create an account or log in, and start a new project.
- Get the Project Keys: Once your project is ready, retrieve the URL and public API key from the project settings.
Integrating Supabase in Your Flutter App
Add the Supabase Flutter dependencies in your pubspec.yaml
file:
dependencies:
supabase_flutter: ^latest_version
Initialize Supabase in your Flutter app:
import 'package:supabase_flutter/supabase_flutter.dart';
void main() {
Supabase.initialize(
url: 'your-supabase-url',
anonKey: 'your-supabase-anon-key',
);
runApp(MyApp());
}
Database Operations with Supabase
Supabase uses Postgres, a powerful SQL database. Let’s cover the CRUD operations:
Create (Insert Data)
Inserting data into a Supabase table:
Future<void> addUser() async {
final response = await Supabase.instance.client
.from('users')
.insert({'username': 'johndoe', 'status': 'ONLINE'})
.execute();
if (response.error != null) {
// Handle the error
}
}
Read (Query Data)
Querying data from a table:
Future<void> getUsers() async {
final response = await Supabase.instance.client
.from('users')
.select()
.execute();
if (response.error != null) {
// Handle the error
} else {
final List<dynamic> data = response.data;
// Work with the data
}
}
Update (Modify Data)
Updating existing records:
Future<void> updateUser(String userId) async {
final response = await Supabase.instance.client
.from('users')
.update({'status': 'OFFLINE'})
.match({'id': userId})
.execute();
if (response.error != null) {
// Handle the error
}
}
Delete (Remove Data)
Deleting records from a table:
Future<void> deleteUser(String userId) async {
final response = await Supabase.instance.client
.from('users')
.delete()
.match({'id': userId})
.execute();
if (response.error != null) {
// Handle the error
}
}
Real-Time Subscriptions
Supabase offers real-time capabilities to subscribe to database changes:
void realtimeSubscription() {
Supabase.instance.client
.from('users')
.on(SupabaseEventTypes.insert, (payload) {
// Handle real-time insert event
})
.subscribe();
}
Authentication with Supabase
Supabase provides an authentication solution that supports email/password, magic link, and third-party logins.
Email/Password Authentication
Sign up and sign in users with email and password:
Future<void> signUpUser(String email, String password) async {
final response = await Supabase.instance.client.auth.signUp(email, password);
// Handle the response
}
Future<void> signInUser(String email, String password) async {
final response = await Supabase.instance.client.auth.signIn(email: email, password: password);
// Handle the response
}
Magic Link Authentication
Sign in users using a magic link:
Future<void> signInWithMagicLink(String email) async {
final response = await Supabase.instance.client.auth.signIn(email: email);
// Handle the response
}
Storage with Supabase
Supabase’s storage solution allows you to manage user-generated content, such as images and documents.
Uploading Files
Future<void> uploadFile(String filePath, String fileName) async {
final file = File(filePath);
final response = await Supabase.instance.client.storage
.from('avatars')
.upload(fileName, file);
if (response.error != null) {
// Handle error
}
}
Retrieving Files
Future<String> downloadFile(String fileName) async {
final response = await Supabase.instance.client.storage
.from('avatars')
.download(fileName);
if (response.error != null) {
// Handle error
} else {
final String url = response.data;
// Use the file URL
return url;
}
}
Conclusion
Integrating Supabase with Flutter opens up a wide array of functionalities, from handling databases with Postgres to real-time data subscriptions, user authentication, and file storage. Supabase’s compatibility with Flutter makes it an excellent choice for developers looking for an open-source and comprehensive backend solution. While this guide covers the fundamental aspects, Supabase’s full potential can be harnessed by exploring its extensive documentation and community resources.