# 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:

| Service | Use case | Package |
|---|---|---|
| [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][firebase-auth] | User sign-in with email, phone, and providers like Google or Apple | [`firebase_auth`][] |
| [Cloud Storage for Firebase][firebase-storage] | File uploads and downloads for user photos, videos, and documents | [`firebase_storage`][] |
| [Firebase AI Logic][firebase-ai] | Direct client access to Gemini and Imagen models | [`firebase_ai`][] |
| [Cloud Functions for Firebase][firebase-functions-dart] | Serverless backend logic written in JavaScript, TypeScript, Python, or Dart (experimental) | [`cloud_functions`][] (client), [`firebase_functions`][] (server) |
| [Firebase Crashlytics][crashlytics] | Realtime crash reporting and diagnostics | [`firebase_crashlytics`][] |

{:.table .table-striped}

For a complete list of supported packages and platform availability,
check out [Available Firebase Flutter plugins][Firebase 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:

   ```console
   $ firebase login
   ```

2. Install the FlutterFire CLI globally:

   ```console
   $ dart pub global activate flutterfire_cli
   ```

3. From the root of your Flutter project, add the core plugin and run
   the configuration workflow:

   ```console
   $ 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][started].

## Authenticate users with Firebase Authentication

[Firebase Authentication][firebase-auth] 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`][]:

```console
$ 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][firebase-auth] or
the [FirebaseUI authentication codelab][auth-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][choose-db].

To add Cloud Firestore to your project, run:

```console
$ 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][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:

```console
$ 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][choose-db]. To set up a
SQL Connect backend and call it from Flutter, follow the guide to
[use generated Flutter SDKs][sql-connect-flutter].

## 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][firebase-functions-dart] using
the [`firebase_functions`][] and [`firebase_admin_sdk`][] packages.

:::note
Dart support for Cloud Functions for Firebase is experimental.
You must enable the `dartfunctions` experiment in the Firebase CLI
before running `firebase init functions`, and the APIs might change
before a stable release.
:::

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][dart-server].

## Flutter and Firebase resources

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

### Documentation and codelabs

* [Add Firebase to your Flutter app][started]
* [Choose a database for your Flutter app][choose-db]
* [Get to know Firebase for Flutter codelab][codelab1]
* [Add a user authentication flow using FirebaseUI][auth-codelab]
* [Firebase AI Logic documentation][firebase-ai]
* [Use Firebase to host your Flutter app on the web][article]

### Videos

* [Get to know Firebase for Flutter video workshop][workshop]
* [Using Firestore as a backend to your Flutter app][video]
* [Live Coding Firebase Authentication with Flutter][video2]

[article]: https://blog.flutter.dev/must-try-use-firebase-to-host-your-flutter-app-on-the-web-852ee533a469
[auth-codelab]: https://firebase.google.com/codelabs/firebase-auth-in-flutter-apps
[choose-db]: /data-and-backend/persistence/choose-a-database
[Cloud Firestore]: https://firebase.google.com/docs/firestore
[`cloud_firestore`]: https://pub.dev/packages/cloud_firestore
[`cloud_functions`]: https://pub.dev/packages/cloud_functions
[codelab1]: https://codelabs.developers.google.com/codelabs/firebase-get-to-know-flutter
[crashlytics]: https://firebase.google.com/docs/crashlytics/flutter/get-started
[dart-server]: https://dart.dev/server#sharing-code-between-flutter-apps-and-dart-backends
[firebase-ai]: https://firebase.google.com/docs/ai-logic/get-started
[`firebase_ai`]: https://pub.dev/packages/firebase_ai
[`firebase_admin_sdk`]: https://pub.dev/packages/firebase_admin_sdk
[firebase-auth]: https://firebase.google.com/docs/auth/flutter/start
[`firebase_auth`]: https://pub.dev/packages/firebase_auth
[Firebase CLI]: https://firebase.google.com/docs/cli
[`firebase_crashlytics`]: https://pub.dev/packages/firebase_crashlytics
[`firebase_data_connect`]: https://pub.dev/packages/firebase_data_connect
[firebase-functions-dart]: https://firebase.google.com/docs/functions/start-dart
[`firebase_functions`]: https://pub.dev/packages/firebase_functions
[Firebase plugins]: https://firebase.google.com/docs/flutter/setup#available-plugins
[Firebase SQL Connect]: https://firebase.google.com/docs/sql-connect
[firebase-storage]: https://firebase.google.com/docs/storage/flutter/start
[`firebase_storage`]: https://pub.dev/packages/firebase_storage
[firestore-quickstart]: https://firebase.google.com/docs/firestore/quickstart
[sql-connect-flutter]: https://firebase.google.com/docs/sql-connect/flutter-sdk
[started]: https://firebase.google.com/docs/flutter/setup
[video]: https://www.youtube.com/watch/DqJ_KjFzL9I&t#38s
[video2]: https://www.youtube.com/watch/OlcYP6UXlm8
[workshop]: https://www.youtube.com/watch/4wunbF29Kkg

