gpt4 book ai didi

firebase - List 不是 List

转载 作者:IT王子 更新时间:2023-10-29 07:22:36 25 4
gpt4 key购买 nike

我有一个带有 questions 的 Cloud Firebase 数据库收藏。每个question有 map 列表options .我正在使用 Flutter 并为 question 设置了以下类和 option :

class Question {
final String text;
final List<Option> options; // I have tried changing this to List<dynamic> but it doesn't help
final String reference;

Question(this.text, this.options, this.reference);

Question.fromMap(Map<String, dynamic> map, {this.reference}) :
text = map['text'],
options = map['options']; // here the error happens

Question.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.documentID);
}

option

class Option {
final String text;
final int votes;
bool isSelected;

Option(this.text, this.votes, this.isSelected);

Option.fromMap(Map<String, dynamic> map) :
text = map['text'],
votes = map['votes'];
}

我真的不知道该如何解决这个问题。不过,这种错误似乎在互联网上无处不在。任何帮助表示赞赏。

更新

供您引用:options是 Cloud Firestore 中的 map 数组。

我根据以下两个答案将代码更改为:

factory Question.fromMap(Map<String, dynamic> map) {

var options = map['options'];
var text = map['text'];
var reference = map['documentID'];
List<Option> optionsList = options.cast<Option>();

return new Question(
text = text,
options = optionsList,
reference = reference
);
}

factory Question.fromSnapshot(DocumentSnapshot snapshot) {
return Question.fromMap(snapshot.data);
}

我仍然收到此错误:type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Option' in type cast

我已经看到并尝试了很多答案,而且似乎都说了同样的话。我就是想不通。

Cloud Firestore 的屏幕截图:

enter image description here

最佳答案

我以前遇到过这个问题,我用

解决了

这是我的代码,您可以将其转换为您的代码:

UserModel.fromSnapshot(DocumentSnapshot snapshot)
: documentReference = snapshot.reference,
username = snapshot['username'],
firstName = snapshot['firstName'],
lastName = snapshot['lastName'],
picture = snapshot['picture'],
routes = Map.from(snapshot['routes']),
avgScore = snapshot['avgScore'];
}

您在 cloud_firestore 上的字段类型是什么?

如果它是一个 Map 尝试使用 Map.from()

如果它是一个 List 尝试使用 List.from()

并将您的本地字段更改为相同类型。

关于firebase - List<dynamic> 不是 List<Option> 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54851001/

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