Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
282 changes: 254 additions & 28 deletions sites/docs/src/content/data-and-backend/firebase.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,286 @@
---
title: Firebase
description: How to use Firebase and Firestore with Flutter.
description: >-
Connect your Flutter app to Firebase for authentication, Cloud Firestore,
Firebase SQL Connect, cloud storage, AI features, and serverless Dart
functions.
---

Firebase is a Backend-as-a-Service (BaaS) app development platform
that provides hosted backend services such as cloud databases
([Cloud Firestore][] and [Firebase SQL Connect][]),
cloud storage, authentication, crash reporting, AI features,
remote configuration, and hosting for your static files.
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:

## Flutter and Firebase resources
| 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`][] |

Firebase supports Flutter. To learn more,
check out the following resources.
{:.table .table-striped}

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

* [Getting started with Firebase and Flutter][started]
* [Choose a database for your Flutter app][choose-db]
* [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();
},
);
}
}

### Blog Posts
Future<UserCredential> signInWithEmail(String email, String password) {
return FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
}
```

[Use Firebase to host your Flutter app on the web][article]
To learn more, check out
[Get started with Firebase Authentication on Flutter][firebase-auth] or
the [FirebaseUI authentication codelab][auth-codelab].

### Tutorials
## Store and sync NoSQL data with Cloud Firestore

Get to know Firebase for Flutter
* [tutorial][codelab1]
* [video workshop][workshop]
[Cloud Firestore][] is the recommended default when your app needs a
scalable NoSQL database that syncs data across devices in realtime and
works offline—such as in chat apps, collaborative tools, or
offline-first field service apps. To compare Cloud Firestore with
relational and local storage options, check out
[Choose a database for your Flutter app][choose-db].

## Flutter and Firebase community resources
To add Cloud Firestore to your project, run:

The Flutter community created the following useful resources.
```console
$ flutter pub add cloud_firestore
```

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

[Building chat app with Flutter and Firebase][chat app]
```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 StatelessWidget {
const TaskList({super.key});

@override
Widget build(BuildContext context) {
final tasksStream = FirebaseFirestore.instance
.collection('tasks')
.orderBy('createdAt', descending: true)
.snapshots();

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, from your schema and queries.

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]
* [Flutter & Firebase Auth 01][video3]
* [Flutter: Firebase Tutorial Part 1 - Auth and Sign in][video4]

[article]: {{site.flutter-blog}}/must-try-use-firebase-to-host-your-flutter-app-on-the-web-852ee533a469
[chat app]: https://medium.com/flutter-community/building-a-chat-app-with-flutter-and-firebase-from-scratch-9eaa7f41782e
[auth-codelab]: {{site.firebase}}/codelabs/firebase-auth-in-flutter-apps
[choose-db]: /data-and-backend/persistence/choose-a-database
[Cloud Firestore]: {{site.firebase}}/docs/firestore
[`cloud_firestore`]: {{site.pub-pkg}}/cloud_firestore
[`cloud_functions`]: {{site.pub-pkg}}/cloud_functions
[codelab1]: {{site.codelabs}}/codelabs/firebase-get-to-know-flutter
[crashlytics]: {{site.firebase}}/docs/crashlytics/flutter/get-started
[dart-server]: {{site.dart-site}}/server#sharing-code-between-flutter-apps-and-dart-backends
[firebase-ai]: {{site.firebase}}/docs/ai-logic/get-started
[`firebase_ai`]: {{site.pub-pkg}}/firebase_ai
[`firebase_admin_sdk`]: {{site.pub-pkg}}/firebase_admin_sdk
[firebase-auth]: {{site.firebase}}/docs/auth/flutter/start
[`firebase_auth`]: {{site.pub-pkg}}/firebase_auth
[Firebase CLI]: {{site.firebase}}/docs/cli
[`firebase_crashlytics`]: {{site.pub-pkg}}/firebase_crashlytics
[`firebase_data_connect`]: {{site.pub-pkg}}/firebase_data_connect
[firebase-functions-dart]: {{site.firebase}}/docs/functions/start-dart
[`firebase_functions`]: {{site.pub-pkg}}/firebase_functions
[Firebase plugins]: {{site.firebase}}/docs/flutter/setup#available-plugins
[Firebase SQL Connect]: {{site.firebase}}/docs/sql-connect
[firebase-storage]: {{site.firebase}}/docs/storage/flutter/start
[`firebase_storage`]: {{site.pub-pkg}}/firebase_storage
[firestore-quickstart]: {{site.firebase}}/docs/firestore/quickstart
[sql-connect-flutter]: {{site.firebase}}/docs/sql-connect/flutter-sdk
[started]: {{site.firebase}}/docs/flutter/setup
[video]: {{site.yt.watch}}/DqJ_KjFzL9I&t#38s
[video2]: {{site.yt.watch}}/OlcYP6UXlm8
[video3]: {{site.yt.watch}}/u_Lyx8KJWpg
[video4]: {{site.yt.watch}}/13-jNF984C0
[workshop]: {{site.yt.watch}}/4wunbF29Kkg
2 changes: 1 addition & 1 deletion sites/docs/src/content/llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ This file provides a curated list of resources to help Large Language Models und
- [Choose a database for your Flutter app](https://docs.flutter.dev/data-and-backend/persistence/choose-a-database): Compare database options for Flutter apps, including Cloud Firestore (recommended default for cloud NoSQL and offline sync), Firebase SQL Connect (recommended default for cloud PostgreSQL with generated type-safe Dart SDKs), on-device SQLite (`sqflite` and `drift`), and key-value storage (`shared_preferences` and `flutter_secure_storage`).
- [Fetch data from the internet](https://docs.flutter.dev/cookbook/networking/fetch-data): Make a basic HTTP request.
- [Networking with Flutter](https://docs.flutter.dev/data-and-backend/networking): How to make HTTP requests and handle JSON data.
- [Firebase for Flutter](https://docs.flutter.dev/data-and-backend/firebase): A guide to using Firebase as a backend for your Flutter app.
- [Firebase for Flutter](https://docs.flutter.dev/data-and-backend/firebase): Connect your Flutter app to Firebase with `flutterfire configure`, authenticate users with `firebase_auth`, sync NoSQL data with `cloud_firestore`, query PostgreSQL with `firebase_data_connect`, and share Dart code with the experimental `firebase_functions` SDK.
- [Persist data with SQLite](https://docs.flutter.dev/cookbook/persistence/sqlite): Learn the basics of local database storage.
- [Store key-value data on disk](https://docs.flutter.dev/cookbook/persistence/key-value): For simple data storage using `shared_preferences`.

Expand Down
Loading