firebase - 如何从Firestore检索List <Map <String,dynamic >>?

标签 firebase flutter dart google-cloud-firestore

我正在尝试创建一个List [Map [String,dynamic]]并将其保存到firestore中并进行检索。问题出在列表上,它给了我:type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>'
我真正想要做的就是将下面的属性保存到“类”列表中,并检索它们的索引以显示在屏幕上。


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 });

}


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

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


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

数据库服务
  // 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"], 
    );
  }

最佳答案

发生该错误的原因是,当您尝试从快照中取回一个数组字段时,它仅知道该字段是一个数组,但实际上不知道该数组包含的数据类型。您可以使用如下形式:

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"], 
 );
}

最简单的解决方案是使您的类列出一个List<dynamic>。尽管它的缺点是在某些地方没有强类型检查,但是它可以工作。

关于firebase - 如何从Firestore检索List <Map <String,dynamic >>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60766138/

相关文章:

reactjs - 使用 firebase-functions 部署基于 React 的 SSR 应用程序时出错

android - 如何用 Flutter 应用替换现有的原生 Android/iOS 应用?

Flutter如何让一行粘在底部

flutter - 使用GlobalKey触发另一个状态功能

dart - 为什么我可以将 List<dynamic> 分配给 List<String>?

api - 使用zoom oauth2和flutter_web_auth的无效重定向错误

java - 如何获取 firebase 数据库中的特定键并比较它们是否相同?

firebase - 有人可以向我解释fromMap()和Snapshot()

android - Firebase.initializeApp();和 FirebaseMessaging.instance.getToken() 抛出 android native 异常

flutter : `camera_android` threw an error: Binding has not yet been initialized