【问题标题】:Flutter | how to retrieve a list of objects from firestore?颤振 |如何从firestore中检索对象列表?
【发布时间】:2020-04-07 22:47:17
【问题描述】:

我需要从 firestore this the structure 检索此列表“项目” 通过这段代码

Future<void> fetchCategories(String userId) async {
return databaseReference
    .collection('/categories/$userId/cats/')
    .snapshots()
    .listen((data) {
  data.documents.forEach((doc) {
    categories.add(Category(
      id: doc.documentID,
      items:   ,
      title: doc.data['title'],
    ));
  });
});

“items”属性是 CategoryItem 对象的列表

 class CategoryItem {
   String id;
   String title;
   String imageUrl;
   String description;

  CategoryItem({
    @required this.id,
    @required this.title,
    this.imageUrl,
    @required this.description,
  });

  CategoryItem.fromMap(Map<String,Object> data):
    id=data['id']??'',
    title=data['title']??'',
    imageUrl=data['imageUrl']??'',
    description=data['description']??'';

}

【问题讨论】:

  • 您好,您可以使用FirebaseAnimatedList 小部件轻松传播数据。 stackoverflow.com/questions/46912713/…
  • @Blasanka 您好,感谢您的回复,但由于某些原因,我需要先检索我的数据,然后将其显示在自定义列表视图中,所以我首先需要我的数据,这是我的问题跨度>

标签: flutter google-cloud-firestore


【解决方案1】:

这就是答案

Future<void> fetchCategories(String userId) async {
    return databaseReference
        .collection('/categories/$userId/cats/')
        .snapshots()
        .listen((data) {
      data.documents.forEach((doc) {
        categories.add(Category(
          id: doc.documentID,
          items:  [...(doc.data['items']).map((items){return CategoryItem.fromMap(items);})],
          title: doc.data['title'],
        )); 
      });
    });


class CategoryItem {
   String id;
   String title;
   String imageUrl;
   String description;

  CategoryItem({
    @required this.id,
    @required this.title,
    this.imageUrl,
    @required this.description,
  });

  CategoryItem.fromMap(Map<dynamic,dynamic> data):
    id=data['id']??'',
    title=data['title']??'',
    imageUrl=data['imageUrl']??'',
    description=data['description']??'';

}

【讨论】:

  • 太好了,你找到了答案。一件事,您不必扩展列表...,只需将.toList() 添加到您的地图功能。 map((items){return CategoryItem.fromMap(items);}).toList()
  • @Blasanka ty ^_^
猜你喜欢
  • 1970-01-01
  • 2020-08-13
  • 2021-04-14
  • 1970-01-01
  • 2021-10-09
  • 2020-08-09
  • 1970-01-01
  • 2020-08-05
  • 2020-01-20
相关资源
最近更新 更多