DEV Community

Salami
Salami

Posted on

Building a Flutter Mobile App with Supabase Integration

Introduction to Supabase

Supabase is an open-source alternative to Firebase that provides a suite of backend services, including databases, authentication, and real-time capabilities. In this article, we'll explore how to create a Flutter mobile app with null safety and integrate it with Supabase for seamless data storage and authentication.

Setting Up Your Flutter Null Safety Project

  1. Create a new Flutter project with null safety enabled:
   flutter create my_supabase_app
Enter fullscreen mode Exit fullscreen mode
  1. Navigate to the project directory:
   cd my_supabase_app
Enter fullscreen mode Exit fullscreen mode
  1. Open the pubspec.yaml file and add the necessary dependencies:
   dependencies:
     flutter:
       sdk: flutter
     supabase_flutter: ^0.4.1 # Supabase SDK for Flutter
Enter fullscreen mode Exit fullscreen mode
  1. Run flutter pub get to install the dependencies.

Initializing Supabase

In your main.dart file, initialize Supabase with your Supabase URL and API key:

import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SupabaseProvider(
      url: 'YOUR_SUPABASE_URL',
      anonKey: 'YOUR_SUPABASE_ANON_KEY',
      child: MaterialApp(
        title: 'Supabase App',
        home: HomeScreen(),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Authenticating with Supabase

Implement user authentication using Supabase in your HomeScreen:

import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final supabase = Supabase.instance.client;
    final session = supabase.auth.currentSession;

    return Scaffold(
      appBar: AppBar(
        title: Text('Supabase App'),
      ),
      body: Center(
        child: session?.accessToken != null
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('You are logged in!'),
                  ElevatedButton(
                    onPressed: () async {
                      await supabase.auth.signOut();
                    },
                    child: Text('Sign Out'),
                  ),
                ],
              )
            : ElevatedButton(
                onPressed: () async {
                  final response = await supabase.auth.signIn(
                    ProviderCredentials.anonymous(),
                  );
                  if (response.error == null) {
                    print('Logged in anonymously');
                  } else {
                    print('Error: ${response.error?.message}');
                  }
                },
                child: Text('Log In Anonymously'),
              ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Storing Data with Supabase

You can easily interact with Supabase's database using the supabase_flutter package. Here's an example of how to insert data into a table:

import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class DataScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final supabase = Supabase.instance.client;

    Future<void> insertData() async {
      final response = await supabase.from('data').upsert([
        {
          'id': 1,
          'name': 'John Doe',
          'email': 'john@example.com',
        },
      ]).execute();
      if (response.error == null) {
        print('Data inserted successfully');
      } else {
        print('Error: ${response.error?.message}');
      }
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('Data Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            await insertData();
          },
          child: Text('Insert Data'),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion: Empower Your Flutter App with Supabase

Integrating Supabase with your Flutter null safety mobile app empowers you to build robust and feature-rich applications. By utilizing Supabase's authentication and database capabilities, you can create user-friendly and efficient apps that store data securely and provide a seamless user experience.

This article merely scratches the surface of what you can achieve with Supabase and Flutter. Dive deeper into Supabase's features, including real-time capabilities, triggers, and more, to further enhance your app's functionality.

Feel free to reach out to me on Twitter @gideonsalamii for more insights into building powerful Flutter apps with Supabase.

Happy coding!

Top comments (0)