简体   繁体   中英

How to retrieve a List<Map<String, dynamic>> from Firestore?

I am trying to create a List[Map[String, dynamic]] and save it into firestore and retrieve it. The issue is with the List, and it's giving me: type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>'

All I really am trying to do here is have the properties below saved into the list 'classes' and retrieve their indexes to show on the screen.

Class

class Cards {
  final List<String> question;
  final List<String> answer;
  final String title;
  final String uid;
  final List<Map<String, dynamic>> classes;

  Cards({  this.question,  this.answer, this.uid,  this.indexTitle, this.classes });

}

Home

List<Map<String, dynamic>> listMap = [];

 listMap.add({ 
   "title": title,
   "question": [],
   "answer": []
  });


DatabaseService(uid: userId.uid).settingUserData(listMap);

DB service

  // Set data to firestore db
  Future settingUserData(List<Map<String, dynamic>> listMap) async {
    return await _collref.document(uid).setData({ 
      "classes": listMap  
      });
  }



Cards _indexCardFromSnapshot(DocumentSnapshot snapshot) {
    return Cards(   
      uid: uid,  
      classes: snapshot.data["classes"], // type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>'
      indexTitle: snapshot.data["indexTitle"],
      question: snapshot.data["question"],
      answer: snapshot.data["answer"], 
    );
  }

The error occurs because when you try to retrieve an array field back from the snapshot it only knows that the field is an array but doesn't actually know what type of data the array contains. You can use something like this:

Cards _indexCardFromSnapshot(DocumentSnapshot snapshot) {
return Cards(   
  uid: uid,  
  classes: List<Map<String,dynamic>>.generate(
      snapshot.data["classes"].length,
      (int index) => Map<String,dynamic>
                     .from(snapshot.data["classes"].elementAt(index));
  ), 
  indexTitle: snapshot.data["indexTitle"],
  question: snapshot.data["question"],
  answer: snapshot.data["answer"], 
 );
}

The simplest solution is to make your classes list a List<dynamic> . Although it has a disadvantage of having no strong type checking at some places but it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM