Monday, June 24, 2024
Google search engine
HomeDevelopersSupabase Database with Flutter: Building Powerful Apps with Real-Time Functionality

Supabase Database with Flutter: Building Powerful Apps with Real-Time Functionality

Learn how to integrate Supabase, an open-source Firebase alternative, with your Flutter app for a powerful and scalable backend solution.

This blog will explore the Supabase Database with Flutter: Building Powerful Apps with Real-Time Functionality. We will also implement a demo program, and learn how to integrate Supabase in your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents :

Introduction — Flutter

What is Supabase?

Features

Getting started with Supabase

Integration of Supabase into Flutter

Code Implementation

Final Output

Conclusion

Github Link

Reference


Introduction:-

Flutter has emerged as a popular choice for building cross-platform mobile applications due to its ease of use and impressive performance. When it comes to integrating a robust backend database into your Flutter app, Supabase offers an excellent solution. In this blog, we’ll explore Supabase and how you can leverage its features to power your Flutter app with a powerful and scalable database. Let’s dive in!

What is Supabase?

In today’s fast-paced world, building powerful and responsive applications is essential to meet the demands of users. And when it comes to developing data-driven applications with real-time functionality, having a robust and scalable backend is crucial. Enter Supabase, an open-source Backend-as-a-Service (BaaS) solution that combines the best of Firebase and traditional databases. It is built on top of PostgreSQL and extends its capabilities with additional features like real-time and Authentication. With Supabase, you get a scalable, secure, and real-time database that can seamlessly integrate with your Flutter app.

In this blog post, we will explore the integration of Supabase with Flutter, allowing you to leverage its real-time database and authentication features to build dynamic and interactive apps. We will delve into the key concepts of Supabase and demonstrate how it empowers developers to create applications that scale effortlessly while maintaining data integrity and security.

Whether you’re a seasoned Flutter developer or just starting your journey, this guide will provide you with a comprehensive understanding of Supabase and its integration with Flutter. By the end, you’ll be equipped with the knowledge to develop powerful, real-time applications backed by a reliable and scalable database solution.

Features:-

  • Managing Data with Supabase

Supabase simplifies data management in your Flutter app. You can use the SupabaseClient class to perform queries, inserts, updates, and deletions. Additionally, you can leverage the real-time functionality to subscribe to changes in the database, ensuring that your app’s data remains up-to-date in real time.

  • Securing Your Flutter App with Supabase Authentication

User authentication is crucial for most applications. Supabase offers built-in authentication features, allowing you to authenticate users through various methods like email/password, social logins (Google, Facebook, etc.), and more. We’ll guide you through implementing secure user authentication in your Flutter app using Supabase.

  • Optimizing Performance with Supabase Indexes

Indexes play a vital role in optimizing database performance. Supabase provides the ability to create indexes on frequently queried columns, significantly improving query response times. We’ll explore how to identify the right columns to index and implement them in your Supabase database.

Getting Started with Supabase:

To begin using Supabase in your Flutter app, you need to set up a Supabase project. This involves signing up for an account in the dashboard and creating a new project here.

Once your project is set up, you will receive a URL and API key, essential for accessing the Supabase database.

To get the URL and API key, follow the below guidelines:

  1. After successfully signing in and creating your project, go to the Home option.

2. Navigate to the Project API section below, where you’ll discover the URL and API key of your Supabase project.

Integration of Supabase into Flutter:

With your Supabase project ready, it’s time to integrate it into your Flutter app. You can do this using the Supabase Dart package, which provides a set of APIs to interact with the Supabase backend. Through these APIs, you can perform CRUD operations, manage user authentication, and subscribe to real-time data updates. Follow the below steps to do so:

Import the latest version of the supabase_flutter package in pubspec.yaml file of your Flutter project.

dependencies:
supabase_flutter: ^1.10.9

— Initialise Supabase in the Flutter project by providing the Supabase project’s URL and API key to establish the connection.

Code snippet:

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();

await Supabase.initialize(
url: 'https://***.supabase.co',
anonKey: '***'
);

final supabase = Supabase.instance.client;
runApp(ProviderScope(child: App(supabase: supabase)));
}

Now, armed with the powerful features of Supabase, we are all set to dive into the code implementation.

Code implementation:-

  • main. dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();

await Supabase.initialize(
url: '<Supabase project URL>',
anonKey:
'eyJhbGc...',
);

await AppPreference().initialAppPreference();

final supabase = Supabase.instance.client;
runApp(ProviderScope(child: App(supabase: supabase)));
}

class App extends StatelessWidget {
const App({Key? key, required this.supabase}) : super(key: key);
final SupabaseClient supabase;

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/', routes: <String, WidgetBuilder>{
'/': (_) => SplashPage(supabase: supabase),
'/login': (_) => LoginPage(supabase: supabase),
'/register': (_) => RegisterUser(supabase: supabase),
'/home': (_) => HomeScreen(),
// home: Home(supabase: supabase),
});
}
}

Authentication:-
  • login. dart
class LoginPage extends StatefulWidget {
const LoginPage({super.key, this.supabase});
final SupabaseClient? supabase;

@override
LoginPageState createState() => LoginPageState();
}

class LoginPageState extends State<LoginPage> {

...

Future<void> _signIn() async {
try {
debugPrint("EMAILLL: ${_emailController.text}, PASSS: ${_passwordController.text}");
await widget.supabase?.auth.signInWithPassword(email: _emailController.text, password: _passwordController.text);
if (mounted) {
_emailController.clear();
_passwordController.clear();

_redirecting = true;
Navigator.of(context).pushReplacementNamed('/home');
}
} on AuthException catch (error) {
context.showErrorSnackBar(message: error.message);
} catch (error) {
context.showErrorSnackBar(message: 'Unexpected error occurred');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Center(child: Text('Login')), backgroundColor: Colors.teal),
body: SingleChildScrollView(

...

Padding(
padding: const EdgeInsets.only(top: 25.0),
child: Container(
height: 50,
width: 250,
decoration: BoxDecoration(color: Colors.teal, borderRadius: BorderRadius.circular(20)),
child: TextButton(
// style: ButtonStyle(backgroundColor: MaterialStateColor.resolveWith((states) => Colors.teal), ),
onPressed: () async {
if (_formKey.currentState!.validate()) {
_signIn();
}
},
child: const Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
),
const SizedBox(
height: 130,
),
TextButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) =>
// RegisterUser(supabase: widget.supabase ?? Supabase.instance.client)
SignUpPage(supabase: widget.supabase ?? Supabase.instance.client)
));
},
child: const Text('Don\'t have an account?', style: TextStyle(color: Colors.teal),)),
const SizedBox(
height: 30,
),

...
),
);
}
}

  • signup. dart
class SignUpPage extends StatefulWidget {
const SignUpPage({super.key, required this.supabase});

final SupabaseClient supabase;

@override
SignUpPageState createState() => SignUpPageState();
}

class SignUpPageState extends State<SignUpPage> {

...

Future<void> _signUp() async {
try {
AuthResponse response = await widget.supabase.auth.signUp(
password: _passwordController.text, email: _emailController.text);
if (mounted) {
_redirecting = true;
print("Userrr -- ${response.user}");
_saveId(response.user);
Navigator.of(context).pushReplacementNamed("/register").then(
(value) => context.showSnackBar(message: "Verify your email!"));
setState(() {});
}
} on AuthException catch (error) {
context.showErrorSnackBar(message: error.message);
} catch (error) {
context.showErrorSnackBar(message: 'Unexpected error occurred');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sign Up'),
backgroundColor: Colors.teal,
),
body: SingleChildScrollView(
child:
...

Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.circular(20)),
child: TextButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
if (_passwordController.text ==
_confPasswordController.text) {
_signUp();
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
"Passwords didn't match! Try again.")));
}
}
},
child: const Text(
'Sign Up',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
const SizedBox(
height: 130,
),

...
}
}

You’ll get the entire code below the GitHub Link.

Final Output:-

Now, for a successful login, the email you used during sign-up needs to be verified. After verifying the email, I returned to the app.

Conclusion:-

In this blog, we comprehensively understood the Supabase database and its powerful functionalities. Now, it’s time to apply this knowledge to your projects and delve deeper into the possibilities it offers. Happy exploring!

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:-

GitHub – flutter-devs/supabase_flutter
Contribute to flutter-devs/supabase_flutter development by creating an account on GitHub.github.com

Reference:-

📃 AWS Amplify Docs —

Supabase Docs
Supabase is an open-source Firebase alternative providing all the backend features you need to build a product.supabase.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

PDF with Flutter

Rest API in Flutter

Charts in Flutter

Spinkit In Flutter

Recent Comments