I need to update a document with nested arrays in Firestore with Flutter.
So I need to get the full document into a Map, reorder the maps in the \"sections\" array,
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.
To get map from documentsnapshot use snapshot.data.data
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
Updated September-2020
To get data from a snapshot document you now have to call snapshot.data()
(cloud_firestore 0.14.0 or higher
)