Skip to main content

Firebase

Connect your Flutter app to Firebase for authentication, Cloud Firestore, Firebase SQL Connect, cloud storage, AI features, and serverless Dart functions.

Firebase is Google's app development platform that provides managed backend services for Flutter apps on mobile, web, and desktop. Each Firebase service is available as a separate Firebase Flutter plugin on pub.dev, so you can add only the services your app needs:

ServiceUse casePackage
Cloud Firestore NoSQL document database with realtime sync and built-in offline cache cloud_firestore
Firebase SQL Connect Managed PostgreSQL database with generated, type-safe Dart SDKs firebase_data_connect
Firebase Authentication User sign-in with email, phone, and providers like Google or Apple firebase_auth
Cloud Storage for Firebase File uploads and downloads for user photos, videos, and documents firebase_storage
Firebase AI Logic Direct client access to Gemini and Imagen models firebase_ai
Cloud Functions for Firebase Serverless backend logic written in JavaScript, TypeScript, Python, or Dart (experimental) cloud_functions (client), firebase_functions (server)
Firebase Crashlytics Realtime crash reporting and diagnostics firebase_crashlytics

For a complete list of supported packages and platform availability, check out Available Firebase Flutter plugins.

Connect a Flutter app to Firebase

#

To register your Flutter app with a Firebase project and generate platform configuration files, use the Firebase CLI and FlutterFire CLI:

  1. Install the Firebase CLI and sign in to your Google Account:

    firebase login
    
  2. Install the FlutterFire CLI globally:

    dart pub global activate flutterfire_cli
    
  3. From the root of your Flutter project, add the core plugin and run the configuration workflow:

    flutter pub add firebase_core
    flutterfire configure
    

    This command registers your per-platform apps in your Firebase project and generates lib/firebase_options.dart.

  4. Initialize Firebase in lib/main.dart before calling runApp():

    dart
    import 'package:firebase_core/firebase_core.dart';
    import 'package:flutter/material.dart';
    import 'firebase_options.dart';
    ​
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
      runApp(const MyApp());
    }
    

For detailed platform setup instructions, refer to Add Firebase to your Flutter app.

Authenticate users with Firebase Authentication

#

Firebase Authentication supports sign-in with email and password, phone numbers, anonymous sessions, and federated identity providers such as Google, Apple, and GitHub.

To add Firebase Authentication to your app, install firebase_auth:

flutter pub add firebase_auth

You can listen to FirebaseAuth.instance.authStateChanges() with a StreamBuilder to react whenever a user signs in or out:

dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
​
class AuthGate extends StatelessWidget {
  const AuthGate({super.key});
​
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasData) {
          return HomeScreen(user: snapshot.data!);
        }
        // Your own sign-in UI.
        return const SignInScreen();
      },
    );
  }
}
​
Future<UserCredential> signInWithEmail(String email, String password) {
  return FirebaseAuth.instance.signInWithEmailAndPassword(
    email: email,
    password: password,
  );
}

To learn more, check out Get started with Firebase Authentication on Flutter or the FirebaseUI authentication codelab.

Store and sync NoSQL data with Cloud Firestore

#

Cloud Firestore is the recommended default when your app needs a scalable NoSQL database that syncs data across devices in realtime and offers offline caching and persistence—such as in chat apps, collaborative tools, or field service apps that need to keep working with an unreliable connection. To compare Cloud Firestore with relational and local storage options, check out Choose a database for your Flutter app.

To add Cloud Firestore to your project, run:

flutter pub add cloud_firestore

The following example adds a task document to a tasks collection and streams live query results into a ListView:

dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
​
Future<void> addTask(String title) {
  return FirebaseFirestore.instance.collection('tasks').add({
    'title': title,
    'completed': false,
    'createdAt': FieldValue.serverTimestamp(),
  });
}
​
class TaskList extends StatefulWidget {
  const TaskList({super.key});
​
  @override
  State<TaskList> createState() => _TaskListState();
}
​
class _TaskListState extends State<TaskList> {
  // Create the stream once so that it isn't recreated on every rebuild.
  final Stream<QuerySnapshot<Map<String, dynamic>>> _tasksStream =
      FirebaseFirestore.instance
          .collection('tasks')
          .orderBy('createdAt', descending: true)
          .snapshots();
​
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: _tasksStream,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return const Center(child: Text('Something went wrong.'));
        }
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
​
        final docs = snapshot.data!.docs;
        return ListView.builder(
          itemCount: docs.length,
          itemBuilder: (context, index) {
            final data = docs[index].data();
            return ListTile(
              title: Text(data['title'] as String? ?? ''),
            );
          },
        );
      },
    );
  }
}

Offline persistence is enabled by default on Android and Apple platforms (and can be enabled on the web), so your app can read and write cached documents without a network connection and automatically sync changes when connectivity returns. To get started, follow the Cloud Firestore quickstart.

Query relational SQL data with Firebase SQL Connect

#

If your app needs a relational database, Firebase SQL Connect (formerly Firebase Data Connect) provides a managed PostgreSQL database and generates a type-safe Dart SDK built on the firebase_data_connect package.

To install the plugin, run:

flutter pub add firebase_data_connect

To compare SQL Connect with Cloud Firestore and local SQLite, check out Choose a database for your Flutter app. To set up a SQL Connect backend and call it from Flutter, follow the guide to use generated Flutter SDKs.

Share Dart code with a serverless Firebase backend

#

When your app needs custom server-side logic, background triggers, or administrative access to Firebase services, you can write Cloud Functions for Firebase in Dart using the firebase_functions and firebase_admin_sdk packages.

Using Dart on both your Flutter frontend and your Firebase backend lets you share a single Dart package for data models, JSON serialization, and validation rules across client and server. To learn how to structure a shared-package workspace, check out Sharing code between Flutter apps and Dart backends.

Flutter and Firebase resources

#

To learn more about building Flutter apps with Firebase, check out the following official and community resources.

Documentation and codelabs

#

Videos

#
⌂ Proxy