【问题标题】:How to retrieve a List<Map<String, dynamic>> from Firestore?如何从 Firestore 中检索 List<Map<String, dynamic>>?
【发布时间】:2020-07-01 02:48:32
【问题描述】:

我正在尝试创建一个 List[Map[String, dynamic]] 并将其保存到 firestore 并检索它。问题出在列表上,它给了我:type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Map&lt;String, dynamic&gt;&gt;'

我真正想做的就是将下面的属性保存到“类”列表中,并检索它们的索引以显示在屏幕上。

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

【问题讨论】:

  • 您在检索数据时遇到此错误吗?
  • 是的,很抱歉。尝试将其作为快照接收时出现此错误@AliHussam
  • 你确定这个错误是在'_indexCardFromSnapshot'函数中你试图返回卡的地方吗?
  • 是的,如果我从“_indexCardFromSnapshot”中排除“类”,一切正常,但是当我包含它时,它就会抛出它。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

发生错误是因为当您尝试从快照中检索数组字段时,它只知道该字段是一个数组,但实际上并不知道该数组包含什么类型的数据。你可以使用这样的东西:

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&lt;dynamic&gt;。虽然它的缺点是在某些地方没有强类型检查,但它会起作用。

【讨论】:

  • 现在给我_InternalLinkedHashMap&lt;dynamic, dynamic&gt;' is not a subtype of type 'Map&lt;String, dynamic&gt;
  • 是的,您是否尝试将 temp 变量转换为 Map ?我想你可以使用Map&lt;String, dynamic&gt;.from(temp) 来做到这一点。让我知道它是否有效。
  • 我确实转换了它,这是输出
  • 我用的是那个。我以前见过这个错误,我从这里得到它github.com/flutter/flutter/issues/16589
  • 我试图自己模仿这个问题。我的解决方案似乎工作正常。如果您向我展示您的代码,我将不胜感激。
猜你喜欢
  • 2023-02-08
  • 2021-04-13
  • 2021-03-25
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多