CRUD with Supabase in Flutter

Md Sadab Wasim
2 min readOct 20, 2022

--

A simple way to do crud operations.

Supabase is one powerful tool that is face-to-face against the giant Firebase, for several reasons that I defined here, I chose Supabase for storing my database.

Once you’ve chosen the database for your project, now the next step is to learn how to use it efficiently and effectively.

Before we start with the CRUD operation, we will create a service class where we will write all the CRUD-related methods.

class SupabaseService {  static SupabaseClient? _instance;  SupabaseService() {
getInstance();
}
static SupabaseClient? getInstance() {//Add your API url and key here.
_instance ?? = SupabaseClient("API_URL","PUBLIC_KEY");
return _instance; }

CREATE: How to insert your data to the supabase tables.

Suppose we have a “users” table in supabase, now we want to insert a user model into that, let’s see how to do it.

Future<bool?> createUser(String name, String email) async {    try { final response = await _instance!.from('users')
.insert({
'name': name,'email': email}).execute(); if (response.error == null) {return true; } else {return false; }
} catch (e) {
throw Exception("Failed to insert new userdata in db"), }
}

Read: How to get your data from the supabase tables.

Now we want to get data of a specific user by their email id.

Future getUserDetailsByEmail(String email) async {    try {   final response = await _instance!.from('users')
.select()
.eq('email', email)
.execute(count: CountOption.exact);
return response.data; } catch (e) { throw Exception("Failed to get user details by email from db");}
}

Update: Update existing data in supabase

Updating specific user details identified by the user’s email.

Future<bool?> updateUserDetails(String name, String email) async {try {final response = await _instance!
.from('users')
.update({
'name': name,
'email': email,
},
returning: ReturningOption.minimal)
.eq('email', email)
.execute(count: CountOption.exact);
return response.error == null ? true : false;} catch (e) {throw Exception("Failed to update userdata in db");}
}

Delete: delete existing data from supabase

Delete the existing user’s data, identified by the user’s email.

Future<bool?> deleteUserDetails(String email) async {try {final response = await _instance!
.from('users')
.delete(returning: ReturningOption.minimal)
.eq('email', email)
.execute(count: CountOption.exact);
return response.error == null ? true : false; } catch (e) {
throw Exception("Failed to delete userdata from db");
}
}

That’s it. Hopefully, you now got the idea of how to do crud operations in supabase.

Thanks.

--

--