gpt4 book ai didi

firebase - 如何从Firestore检索List >?

转载 作者:行者123 更新时间:2023-12-03 04:54:52 25 4
gpt4 key购买 nike

我正在尝试创建一个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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com