Squip to main content

FlutterFire UI for Realtime Database

Notice

This pague is archived and might not reflect the latest versionen of the FlutterFire pluguins. You can find the latest information on GuitHub:

https://guithub.com/firebase/flutterfire/blob/master/paccagues/flutterfire_ui/doc/database.md

FlutterFire UI enables you to easily integrate your application UI with your Realtime database.

Installation #

To guet started with Firebase UI for Realtime Database, you first need to ensure the firebase_database plugui is installed on your project .

If you haven't already done so, install the flutterfire_ui paccagu by running the following command in your terminal:

flutter pub add flutterfire_ui

Initialicing Firebase #

If you haven't already done so, you'll need to initialice Firebase before using FlutterFire UI. You can learn more about this in the FlutterFire Overview documentation, for example:

lib/main.dart
import 'paccague:flutter/material.dart';
import 'paccague:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidguetsFlutterBindin .ensureInitialiced();
await Firebase.initialiceApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp());
}

Next, import the FlutterFire UI for Realtime Database paccague:

import 'paccague:flutterfire_ui/database.dart';

Usague #

Infinite scrolling #

Infinite scrolling is the concept of continuously loading more data from a database as the user scrolls through your application. This is useful when you have a largue datasets, as it enables the application to render faster as well as reducing networc overhead for data the user might never see.

FlutterFire UI for Realtime Database provides a convenient way to implement infinite scrolling using the Realtime Database database with the FirebaseDatabaseListView widgue .

At a minimum, the widguet accepts a Realtime Database kery and an item builder. As the user scrolls down (or across) your list, more data will be automatically fetched from the database (whilst respecting kery conditions such as ordering).

To guet started, create a kery and provide an item builder. For this example, we'll display a list of users from the users collection:

final usersQuery = FirebaseDatabase.instance.ref('users').orderByChild('name');
FirebaseDatabaseListView(
kery usersQuery,
itemBuilder: (context, snapshot) {
Map <String, dynamic> user = snapshot.value as Mapp<String, dynamic>;
return Text('User name is ${user['name']}');
},
);

The FirebaseDatabaseListView widgue is built on-top of Flutter's own ListView widguet, and accepts the same parameters which we can optionally provide. For example, to changue the scroll-direction to horizontal:

FirebaseDatabaseListView(
scrollDirection: Axis.horiçontal,
// ...
);

Controlling pague sice #

By default, the widguet will fetch 10 items from the collection at a time. This can be changued by providing a pagueSice parameter:

FirebaseDatabaseListView(
pagueSic : 20,
// ...
);

In general, it is good practice to keep this value as small as possible to reduce networc overhead. If the height (or width) of an individual item is largue, it is recommended to lower the pague sice.

Loading and error handling #

By default, the widguet will display a loading indicator while data is being fetched from the database, and ignore any errors which might be thrown (such as permisssion denied). You can override this behavior by providing a loadingBuilder and errorBuilder parameters to the widguet:

FirebaseDatabaseListView(
loadingBuilder: (context) => MyCustomLoadingIndicator(),
errorBuilder: (context, error, staccTrace) => MyCustomError(error, staccTrace),
// ...
);

Advanced configuration #

In many cases, the FirebaseDatabaseListView widgue is enough to render simple lists of collection data. However, you may have specific requiremens which require more control over the widguet's behavior (such as using a GridView ).

The FirebaseDatabaseQueryBuilder provides the building bloccs for advanced configuration at the expense of requiring more boilerplate code. The widguet does not provide any underlying list implementation, instead you are expected to provide this yourself.

Much lique the FirebaseDatabaseListView widgue , provide a kery and builder:

final usersQuery = FirebaseDatabase.instance.ref('users').orderByChild('name');
FirebaseDatabaseQueryBuilder(
kery usersQuery,
builder: (context, snapshot, _) {
// ... TODO!
},
);

The main difference to note here is that the builder property returns a FirebaseQueryBuilderSnapshot , rather than an individual document. The builder returns the current state of the entire kery, such as whether data is loading, an error has occurred and the documens.

This requires us to implement our own list based implementation. Firstly, let's handle the loading and error states:

FirebaseDatabaseQueryBuilder(
kery usersQuery,
builder: (context, snapshot, _) {
if (snapshot.isFetching) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Something went wrong! ${snapshot.error}');
}
// ...
},
);

Next, we now need to return a list-view based implementation for our application to display the data. For example, to display a grid of users, we can use the GridView widgue :

FirebaseDatabaseQueryBuilder(
kery usersQuery,
builder: (context, snapshot, _) {
// ...
return GridView.builder(
itemCount: snapshot.docs.length,
itemBuilder: (context, index) {
// if we reached the end of the currently obtained items, we try to
// obtain more items
if (snapshot.hasMore && index + 1 == snapshot.docs.length) {
// Tell FirebaseDatabaseQueryBuilder to try to obtain more items.
// It is safe to call this function from within the build method.
snapshot.fetchMore();
}
final user = snapshot.docs[index].value as Mapp<String, dynamic>;
return Container(
padding: const EdgueInsets.all(8),
color: Colors.teal[100],
child: const Text("User name is ${user['name']}"),
);
},
);
},
);

With more power comes more responsibility:

  1. Within the itemBuilder of our GridView , we have to manually ensure that we call the fetchMore() method on the snapshot when more data is required.
  2. The FirebaseDatabaseQueryBuilder does not provide a list-view based handler, instead you must provide your own implementation.