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!');
}
});
}
}
- Use FutureBuilder
- Pass
Future<QuerySnapshot>
to futureFirebaseFirestore.instance.collection('posts').get()
If you reference an old tutorial you might findgetDocuments()
, but it's deprecated. Now it is replaced withget()
- Retrieve
List<DocumentSnapshot>
from a snapshot. You can use methods likemap()
.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!');
}
});
}
}
- Use
StreamBuilder
Pass
Stream<QuerySnapshot>
to stream
FirebaseFirestore.instance.collection('posts'). snapshot()
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!!
Top comments (2)
Get article, but how can I snapshot "a document with specific ID"...?
your vsCode Theme?