How to use StreamBuilder with Firestore in Flutter

In the course of learning how to develop mobile app using flutter, you may find the need to store your application data in a cloud real-time database.

One of the most popular cloud database options in flutter is Cloud Firestore.

We will use a simple flutter code example to illustrate and learn how to use StreamBuilder with Firestore in Flutter.

You may be asking yourself what is this StreamBuilder of a thing?

Lets take a brief moment to understand while we use StreamBuilder.

Flutter has support for Stream. A stream provides an asynchronous sequence of data. The data includes user-generated events and data read from files

To have access to this data stream, you will need to subscribe to it. Each event can be a data value or an error that signifies something wrong has happened.

The stream gets to the end when it receives the done event. You can read more about Flutter steam here.

We will go back to StreamBuilder now that we have explore flutter stream.

Imagine you retrieve a data from Firestore inside a widget and your return data is in stream format.

Then you will need to create a widget with the stream. This is where StreamBuilder comes into play.

StreamBuilder is a widget that builds itself based on the latest snapshot of interaction with a Stream.

So whenever there is a new data event, the StreamBuilder rebuild its widget

Let’s go ahead and show a simple flutter project that highlights how to use StreamBuilder with Firestore in Flutter.

Create new Flutter Project

In your Visual Studio Code, go to View menu > Command Palette.

In the open dialog, select Flutter. Enter the name of your Flutter project and hit enter key button.

In the lib folder, open the main.dart file and add the code below.

main.dart

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: StreamBuilderFireStore(),
    );
  }
}

Add Project in Firebase Console

Go to your Firebase console and add a new project.

You will need to download the google_services.json file and add it to your flutter project.

In the database section, select and enable Cloud Firestore.

This link will help you to understand how to create new Firebase project.

Create new Dart file in lib folder

Go to the lib folder and create a dart file. Name the file json_array.dart.

Import Flutter Firestore package and dart async also.

Open the newly created dart file and add the code below.

import 'dart:async';

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

class StreamBuilderFireStore extends StatelessWidget {
  
  Widget _buildList(BuildContext context, DocumentSnapshot document) {
    return ListTile(
      title: Text(document['title']),
      subtitle: Text(document['body']),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("StreamBuilder with FireStore")),
      body: StreamBuilder(
        stream: Firestore.instance.collection('posts').snapshots(),
        //print an integer every 2secs, 10 times
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Text("Loading..");
          }
          return ListView.builder(
            itemExtent: 80.0,
            itemCount: 2,
            itemBuilder: (context, index) {
              return _buildList(context, snapshot.data.documents[index]);
            },
          );
        },
      ),
    );
  }
}

RUN YOUR APP

You can use flutter command to run your app – $ flutter run

If everything goes well, you will see screen similar to the image below in your flutter device.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment