【问题标题】:How to convert Firestore document data into a Class如何将 Firestore 文档数据转换为类
【发布时间】:2021-08-24 05:12:31
【问题描述】:

在 Firestore 中,有一些文档包含 'name' 、 'continent' 等字段及其字符串值。我在主 UI 代码中使用 FutureBuilder,并调用 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;
  }

}

这是控制台的样子:

I/flutter ( 430): this is listData []

这是 HomePageModel 类

class HomePageModel {

  String? name;
  String? docId;
  String? continent;
  HomePageModel({this.docId, this.name, this.continent});
}

我不知道如何将这些从 Firestore 检索到的文档数据模型放在 listData 中,这就是为什么在控制台中 listData 没有任何数据。 谢谢你:)

【问题讨论】:

  • 你能详细说明一下吗,用代码sn-p..我是初学者

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

参数 B.

我认为问题就在这里。

    await locationCollection.get().then((QuerySnapshot querySnapshot){
      querySnapshot.docs.forEach((doc) {
        HomePageModel(
          docId: doc.id,
          continent: doc['continent'],
          name: doc['name']
        );
      });
    });

第一个问题是您没有创建新的对象实例。第二个是您没有将新对象实例添加到列表中。

我没有测试代码,但我认为这会起作用。

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 homepagemodel = new HomePageModel( // the first issue
          docId: doc.id,
          continent: doc['continent'],
          name: doc['name']
        );
        listData.add(homepagemodel); // the second issue
      });
    });
    return listData;
  }

}

还有一件事。我真的不知道在课堂上使用 { } 和 ? 有什么区别,但我从未使用过。我做这样的课。但我认为你的课也有效。

class HomePageModel {
  String name;
  String docId;
  String continent;
  
  HomePageModel(this.docId, this.name, this.continent);
}

还有一件事,打印不适用于项目列表。例如,您需要像这样使用for loop。

for (var i = 0; i < listData.length; i++) {
   print("Loaded data: " + listData[i].name);
}

【讨论】:

猜你喜欢
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
相关资源
最近更新 更多