【发布时间】:2021-05-25 17:27:01
【问题描述】:
我正在尝试将 firestore 文档快照映射到我创建的自定义对象,但这样做时出现此错误:
E/flutter (6555): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:类型“(动态)=> TestMap”不是类型“(字符串,动态)的子类型=> MapEntry
' of 'transform'
据我了解,这与我解析嵌套地图“testMap”的方式有关。那里有任何 Flutter/Firebase/Dart 专家可以帮助我了解我做错了什么以及如何解决这个问题。
所以我在 Firestore 中的数据如下所示:
将这些数据解析为可用对象的两个类对象,如下所示:
class Categories {
final String category;
final String imageurl;
List testMap = [];
Categories(this.category, this.imageurl);
Map<String, dynamic> toMap() => {
"category": this.category,
"imageurl": this.imageurl,
"testMap": this.testMap
};
Categories.fromMap(Map<String, dynamic> map)
: category = map["category"],
imageurl = map["imageurl"],
testMap = map["testMap"].map((map) { // THE ERROR IS HERE (map)
return TestMap.fromMap(map);
}).toList();
}
class TestMap {
final String v1;
final String v2;
TestMap(this.v1, this.v2);
Map<String, dynamic> toMap() => {
"v1": this.v1,
"v2": this.v2,
};
TestMap.fromMap(Map<dynamic, dynamic> map)
: v1 = map["v1"],
v2 = map["v2"];
}
最后我像这样从 Firestore 获取数据:
fromFirestore() {
final FirebaseAuth auth = FirebaseAuth.instance;
Categories categoryObject;
CollectionReference categoriesCollection =
FirebaseFirestore.instance.collection('categories');
categoriesCollection.doc('categories').get()
// ignore: missing_return
.then((docSnapshot) {
for (var i = 1; i <= docSnapshot.data().length; i++) {
print(docSnapshot.data()[i.toString()]['testMap'].toString());
categoryObject = Categories.fromMap(docSnapshot.data()[i.toString()]);
}
});
}
我知道 firestore 映射到 Map
非常感谢!
【问题讨论】:
标签: firebase flutter dart google-cloud-firestore