DEV Community

mukhtharcm
mukhtharcm

Posted on • Originally published at mukhtharcm.com on

Flutter ListView from Firebase Firestore

Introduction

Firebase is a Backend-as-a-Service now owned by Google. There are many serives offered under Firebase. This include but not limited to Cloud Firestore, Realtime Database, Firebase Auth etc.

In these, Cloud Firestore is the newest database solution offered by Firebase. It is widely used in Mobile Application and Web-apps nowadays. So letโ€™s have a look on how to create a ListView out of Firestore Data.

Prerequisites

Before we continue, we should have completed Firebase Setup for our Flutter Application in Both android and iOS by following respective guides for both Android and iOSand Initialized Firebase.

<!-- raw HTML omitted --><!-- raw HTML omitted -->

When trying to show a ListView from Firestore, in Flutter we have 2 options. We can either use FutureBuider or StreamBuilder. If we use StreamBuilder, the data on the List Will updately realtime. So letโ€™s go with 2nd Option.

Coding Time!

First, we have to get an instance of Firestore.

final db = FirebaseFirestore.instance;

Enter fullscreen mode Exit fullscreen mode

Now we can use this instance to call our Firestore Collection.

Suppose we have a collection named notes in Firestore.

Notes Collection

We can put db.collection('notes').snapshots in the stream argument of StreamBuilder.

StreamBuilder(
stream: db.collection('notes').snapshots(),
),

Enter fullscreen mode Exit fullscreen mode

After this, we can continue to our ListView. But it is always a better Idea to check if the Snapshot we are getting is not Empty. So we should check for that also.

So if we have data in Snapshot, we can return our ListView. The snapshot we get when we call a collection is a QuerySnaphotSo as the children of ListView, we can map DocuementSnapshots from this QuerySnapshot

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class NoteList extends StatelessWidget {
final db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Notes"),
centerTitle: true,
),
body: StreamBuilder<QuerySnapshot>(
stream: db.collection('notes').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else
return ListView(
children: snapshot.data.docs.map((doc) {
return Card(
child: ListTile(
title: Text(doc.data()['title']),
),
);
}).toList(),
);
},
),
);
}
}

Enter fullscreen mode Exit fullscreen mode

The above should give you a List of Notes we saw earlier on Firebase Console.

The Screenshot of the app we are building

If you have any suggestion or like to connect with me, you can find me on Twitter or can drop me a Mail at mukhtharcm@gmail.com. ๐Ÿ˜Š

Discussion (0)