【问题标题】:How to convert a sub collection to list with flutter and firestore?如何使用flutter和firestore将子集合转换为列表?
【发布时间】:2019-04-08 01:58:55
【问题描述】:

我有一个包含成分列表的对象 Dish,我想得到它们。我能怎么做? 在 Firebase 中,Dish 是一个文档,而成分是一个子集合。我试过了,但它不起作用。

class Dish{

  String name;
  DocumentReference reference;
  List<Ingredient> ingredients;

  Dish.fromMap(Map<String, dynamic> map, {this.reference}){
    this.name = map['name'];

    this
        .reference
        .collection("ingredients")
        .snapshots()
        .listen((QuerySnapshot snap) {
      final List<DocumentSnapshot> ingredientsDocuments = snap.documents;
      List<Ingredient> ing = [];
      for (var i = 0; i < ingredientsDocuments.length; i++) {
        ing.add(Ingredient.fromSnapshot(ingredientsDocuments[i]));
      }
      this.ingredients = ing;
    });
  }



  Dish.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Dish<$String>";

}

class Ingredient{
  final String name;
  final DocumentReference reference;

  Ingredient.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        name = map['name'];

  Ingredient.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Ingredient<$String>";
}

【问题讨论】:

标签: firebase dart flutter google-cloud-firestore


【解决方案1】:

您如何尝试使用 Dish 类从 Firestore 获取数据?您是否使用了任何异步任务(即Future)?在您的实施中什么不起作用?您收到任何错误信息?

由于我无法运行您提供的重现,因此您可以尝试以下示例代码。

List<Ingredient> ingredients;
// call getDocuments() to fetch data from Firestore and add it to the List
Future<void> getDocuments() async {
  ingredients = List();
 
  var collection = FirebaseFirestore.instance
      .collection('ingredients');
 
  collection.get().then((value) {
    value.docs.forEach((element) {
      setState(() {
        // add the object to the List
        ingredients.add(Ingredient(Ingredient.fromMap(element.data())));
      });
    });
  });
}

至于Object,就这么简单。无需传递 DocumentReference,因为我们只会使用它将数据映射到 Object 并能够将其添加到 List 中。

class Ingredients {
  var name;

  Ingredients(Ingredients document) {
    this.documentName = document.getName();
  }

  dynamic getName() => name;

  Ingredients.fromMap(Map<dynamic, dynamic> document)
      : name = document['name'];
}

您可以查看我在here 中发布的工作示例。它添加了分页,但它应该与我在这里分享的代码 sn-ps 有类似的方法。

【讨论】:

    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多