Convert Firestore DocumentSnapshot To Map In Flutter


Answer :

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



Needed to simplify for purpose of example
enter image description here



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
enter image description here



Updated September-2020


To get data from a snapshot document you now have to call snapshot.data() (cloud_firestore 0.14.0 or higher)



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable