繁体   English   中英

如何将子集合转换为包含 flutter 和 firestore 的列表?

[英]How to convert a sub collection to list with flutter and firestore?

我有一个 object 菜,其中包含成分列表,我想得到它们。 我能怎么做? 在 Firebase 中,Dish 是一个 Document,Ingredient 是一个子集合。 我试过了,但没用。

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>";
}

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

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

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,因为我们将仅使用它来将数据映射到对象并能够将其添加到列表中。

class Ingredients {
  var name;

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

  dynamic getName() => name;

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

您可以查看我在此处发布的工作示例。 它添加了分页,但它应该具有与我在此处共享的代码片段类似的方法。

您也可以使用 Iterable forEach()方法将 Dart Map 转换为 List。

变量列表 = [];

Ingredients.entries.forEach((e) => list.add(Customer(e.key, e.value)));

print(list);

我们将forEach()应用于地图的entries属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM