Convert Firestore DocumentSnapshot to Map in Flutter
As per our discussion snapshot is not a DocumentSnapshot
it is AsyncSnapshot
to get the DocumentSnaphot use snapshot.data
to get the actual map you can use snapshot.data.data()
Which will return the Map<String, dynamic> you are looking for.
Needed to simplify for purpose of example
class ItemsList extends StatelessWidget {
@override
Widget build(BuildContext context) {
// get the course document using a stream
Stream<DocumentSnapshot> courseDocStream = Firestore.instance
.collection('Test')
.document('4b1Pzw9MEGVxtnAO8g4w')
.snapshots();
return StreamBuilder<DocumentSnapshot>(
stream: courseDocStream,
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
// get course document
var courseDocument = snapshot.data.data;
// get sections from the document
var sections = courseDocument['sections'];
// build list using names from sections
return ListView.builder(
itemCount: sections != null ? sections.length : 0,
itemBuilder: (_, int index) {
print(sections[index]['name']);
return ListTile(title: Text(sections[index]['name']));
},
);
} else {
return Container();
}
});
}
}
The Results
Looks like maybe because you got a stream builder, so the Snapshot is a AsyncSnapshot<dynamic>
, when you grab its .data, you get a dynamic, which returns a DocumentSnapshot, which then you need to call .data on this object to get the proper Map<String, dynamic> data
.
builder: (context, snapshot) {
final DocumentSnapshot ds = snapshot.data;
final Map<String, dynamic> map = ds.data;
}
You can also append to arrays using in-built functions, but looks like you wanna do some crazy sorting so all good.
Update May 2021
See Migration to cloud_firestore 2.0.0 here.
//Replace this:
- StreamBuilder<DocumentSnapshot>(
//With this:
+ StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
The type has to be defined when creating variables:
Future<void> example(
- DocumentReference documentReference,
+ DocumentReference<Map<String, dynamic>> documentReference,
- CollectionReference collectionReference,
+ CollectionReference<Map<String, dynamic>> collectionReference,
- Query query,
+ Query<Map<String, dynamic>> query,
) {