Firebase 如何将Firestore文档数据转换为类
在Firestore中,有些文档具有“名称”、“大陆”等字段及其字符串值。我在主UI代码中使用FutureBuilder,并调用Firebase 如何将Firestore文档数据转换为类,firebase,flutter,dart,google-cloud-firestore,Firebase,Flutter,Dart,Google Cloud Firestore,在Firestore中,有些文档具有“名称”、“大陆”等字段及其字符串值。我在主UI代码中使用FutureBuilder,并调用getData()函数 这是我的密码 class DatabaseService { final locationCollection = FirebaseFirestore.instance.collection("location"); Future<List<HomePageModel>> getData()
getData()
函数
这是我的密码
class DatabaseService {
final locationCollection = FirebaseFirestore.instance.collection("location");
Future<List<HomePageModel>> getData() async {
List<HomePageModel> listData = [];
await locationCollection.get().then((QuerySnapshot querySnapshot){
querySnapshot.docs.forEach((doc) {
HomePageModel(
docId: doc.id,
continent: doc['continent'],
name: doc['name']
);
});
});
print("this is listData $listData");
return listData;
}
}
我不知道如何将从Firestore检索到的这些文档数据模型放入listData
中,这就是为什么控制台listData
中没有任何数据。
谢谢:)参数B
我认为问题就在这里
wait locationCollection.get().then((QuerySnapshot QuerySnapshot){
querySnapshot.docs.forEach((doc){
主页模型(
docId:doc.id,
大陆:doc[“大陆”],
名称:doc['name']
);
});
});
第一个问题是您没有创建新的对象实例。第二,您没有将新对象实例添加到列表中
我没有测试代码,但我认为这会起作用。
类数据库服务{
final locationCollection=FirebaseFirestore.instance.collection(“位置”);
Future getData()异步{
列表数据=[];
等待locationCollection.get().then((QuerySnapshot QuerySnapshot){
querySnapshot.docs.forEach((doc){
HomePageModel HomePageModel=新的HomePageModel(//第一期
docId:doc.id,
大陆:doc[“大陆”],
名称:doc['name']
);
listData.add(homepagemodel);//第二个问题
});
});
返回列表数据;
}
}
还有一件事。我真的不知道在类中使用{
}
和?
有什么区别,但我从未使用过它。我上这样的课。但我认为你的课也很有效
类主页模型{
字符串名;
字符串docId;
弦大陆;
HomePageModel(this.docId、this.name、this.contraction);
}
还有一件事,打印对项目列表不起作用。例如,您需要像这样使用for循环
for(var i=0;i
您能用一段代码片段详细说明一下吗。。我是初学者
class HomePageModel {
String? name;
String? docId;
String? continent;
HomePageModel({this.docId, this.name, this.continent});
}