DEV Community

Kazuhide Oki
Kazuhide Oki

Posted on

8

How to get data from Firestore and show it on `FlutterBuilder` or `StreamBuilder`

Alt Text

I'm learning Flutter. I was stacked when I got data from Firestore. So this is a solution to that.

I was confused that there were some deprecated methods and complicated handling of the return value.

Here are examples for using it with FutureBuilder and StreamBuilder.

※ I omitted some steps like Firebase.initializeApp() etc.

FutureBuilder (Read once at first)

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

class HogeApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    // <1> Use FutureBuilder
    return FutureBuilder<QuerySnapshot>(
        // <2> Pass `Future<QuerySnapshot>` to future
        future: FirebaseFirestore.instance.collection('posts').get(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // <3> Retrieve `List<DocumentSnapshot>` from snapshot
            final List<DocumentSnapshot> documents = snapshot.data.docs;
            return ListView(
                children: documents
                    .map((doc) => Card(
                          child: ListTile(
                            title: Text(doc['text']),
                            subtitle: Text(doc['email']),
                          ),
                        ))
                    .toList());
          } else if (snapshot.hasError) {
            return Text('It's Error!');
          }
        });
  }
}

Enter fullscreen mode Exit fullscreen mode
  1. Use FutureBuilder
  2. Pass Future<QuerySnapshot> to future FirebaseFirestore.instance.collection('posts').get() If you reference an old tutorial you might find getDocuments(), but it's deprecated. Now it is replaced with get()
  3. Retrieve List<DocumentSnapshot> from a snapshot. You can use methods like map(). documents is also deprecated.

StreamBuilder (updating data continuously)

It is useful for apps like chatting which requires frequent updates.

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

class HogeApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // <1> Use StreamBuilder
    return StreamBuilder<QuerySnapshot>(
        // <2> Pass `Stream<QuerySnapshot>` to stream
        stream: FirebaseFirestore.instance.collection('posts').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // <3> Retrieve `List<DocumentSnapshot>` from snapshot
            final List<DocumentSnapshot> documents = snapshot.data.docs;
            return ListView(
                children: documents
                    .map((doc) => Card(
                          child: ListTile(
                            title: Text(doc['text']),
                            subtitle: Text(doc['email']),
                          ),
                        ))
                    .toList());
          } else if (snapshot.hasError) {
            return Text('It's Error!');
          }
        });
  }
}

Enter fullscreen mode Exit fullscreen mode
  1. Use StreamBuilder
  2. Pass Stream<QuerySnapshot> to stream
    FirebaseFirestore.instance.collection('posts'). snapshot()

  3. Retrieve List<DocumentSnapshot> from a snapshot. This part is the same as FutureBuilder

Conclusion

  • Pass Future or Stream, then handle a snapshot in builder
  • Reference official document if needed (Because Flutter is updating frequently)

If there are any mistakes please let me know.

Thanks. Have a happy coding!!

Reference

Cloud Firestore | FlutterFire

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (2)

Collapse
 
bkmillanzi profile image
Bkmillanzi

Get article, but how can I snapshot "a document with specific ID"...?

Collapse
 
faizshaikh7 profile image
Faiz Shaikh

your vsCode Theme?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay