1
  static List categoryList() {
    final categorySnapshots = FirebaseFirestore.instance
        .collection('categories')
        .orderBy('name')
        .snapshots();

    List categories = [];
    categorySnapshots.map((snapshot) => snapshot.docs.map((doc) {
          print(snapshot.toString());
          categories.add(doc.data()['name']);
        }));

    print(categories);
    return categories;
  }

Categories is empty. How to populate it with the data from snapshots?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dee Mee
  • 13
  • 3

2 Answers2

0

Using the below code might help

you can convert the snapshot to Map<String,dynamic> by using the following function:

 static Post fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>; 
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 11 '22 at 15:46
0

I added a new collection called "school", there're two items added inside the document.

  void getMessagesTest() async{
    QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age',descending: true).get();
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
    print(allData);
  }

I used my code, and it works. Could you please remove ".where" and try it again?

enter image description here enter image description here

You could chain where and orderBy together. Please see my code below. Reference link => Using Where and Order by different fields in Firestore query

  void getMessagesTest() async{
    QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age', descending: true).where('age', isGreaterThan: 17).get();
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
    print(allData);
  }

Frederic Chang
  • 509
  • 1
  • 5
  • 13