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;
Now we can use this instance to call our Firestore Collection.
Suppose we have a collection named notes in Firestore.
We can put db.collection('notes').snapshots
in the stream argument of StreamBuilder.
StreamBuilder(
stream: db.collection('notes').snapshots(),
),
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 QuerySnaphot
So 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(),
);
},
),
);
}
}
The above should give you a List of Notes we saw earlier on Firebase Console.
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. ๐
Top comments (0)