简体   繁体   English

从子集合 firestore + FLUTTER 中检索信息

[英]Retrieve information from sub collection firestore + FLUTTER

I'm new in flutter and firebase.我是 flutter 和 firebase 的新手。

I have a collection called "dishes" where I have many documents (such as the name, description and so on), I have also a subcollection called ingredients where I have as a documents the id, name and quantity.我有一个名为“dishes”的集合,其中有许多文档(例如名称、描述等),我还有一个名为 components 的子集合,其中包含 id、名称和数量作为文档。

What I'm trying to do is retrieve all dishes with ingredients.我正在尝试做的是检索所有带有配料的菜肴。

I have dishModel我有菜模型

class DishModel{
  static const ID = "id";
  static const DESCRIPTION = "description";
  static const IMAGE = "image";
  static const NAME = "name";
  static const INGREDIENTS = "ingredients";

  int _id;
  String _description;
  String _image;
  String _name;
  double _price;
  int _rates;
  double _rating;
  List<IngredientModel> _ingredients;

//GETTERS

  int get id => _id;

  String get description => _description;


  String get image => _image;



  String get name => _name;

  List<IngredientModel> get ingredients => _ingredients;

  DishModel.fromSnapshot(DocumentSnapshot snapshot){
    _id = snapshot.data()[ID];
    _description = snapshot.data()[DESCRIPTION];
    _image = snapshot.data()[IMAGE];
    _name = snapshot.data()[NAME];
  }
}

IngredientModel成分模型

class IngredientModel{
  static const ID = "id";
  static const NAME = "name";
  static const QUANTITY = "quantity";

  int _id;
  String _name;
  String _quantity;

  //GETTERS

  int get id => _id;

  String get name => _name;

  String get quantity => _quantity;


  IngredientModel.fromSnapshot(DocumentSnapshot snapshot){
    _id = snapshot.data()[ID];
    _name = snapshot.data()[NAME];
    _quantity = snapshot.data()[QUANTITY];

  }


}

DishHelper餐具帮手

class DishServices{
  String collection = "dishes";
  FirebaseFirestore _firestore = FirebaseFirestore.instance;
  String subcollection = "ingredients";

  Future<List<DishModel>> getDishes() async
  {
    DishModel dishTemp ;
    List<DishModel> dishes = [];
    _firestore.collection(collection).get().then((result) {
      for (DocumentSnapshot dish in result.docs) {
        dishTemp = DishModel.fromSnapshot(dish);
        dish.reference.collection(subcollection).get().then((ingredientRes) {
          for(DocumentSnapshot ingredient in ingredientRes.docs) {
            dishTemp.ingredients.add(IngredientModel.fromSnapshot(ingredient));
          }
        });
        dishes.add(dishTemp);
      }
      return dishes;
    });

  }

}

DishProvider DishProvider

class DishProvider with ChangeNotifier{
  DishServices _dishServices = DishServices();
  List<DishModel> dishes = [];

  DishProvider.initialize(){
    _loadDishes();
  }

  _loadDishes() async{
    dishes = await _dishServices.getDishes();
    notifyListeners();
  }


}

in main I wrote我主要写了

 runApp(MultiProvider(providers: [
    ChangeNotifierProvider.value(value: DishProvider.initialize())
  ],
      child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'example_app',
          theme: ThemeData(
            primarySwatch: Colors.red,
          ),
          home: ScreensController()
      )));
}

and in home (in build method)在家里(在构建方法中)

final dishProvider =  Provider.of<DishProvider>(context);

but if I try to print print(dishProvider.dishes);但如果我尝试打印print(dishProvider.dishes); I obtain flutter: null instead of flutter: Instance of 'DishModel'我得到flutter: null而不是 flutter: Instance of 'DishModel'

how I can solve it and retrieve my dish information?我该如何解决它并检索我的菜肴信息?

Thank you all谢谢你们

You need to get the id of the dishes document to retrieve the subcollection.您需要获取菜品文档的 id 来检索子集合。

FirebaseFirestore.instance
              .collection('dishes')
              .doc(docId)
              .collection('ingredients')
              .snapshots(),

Here is a Github repo是一个 Github 回购

I think there is something within the getDishes() loop.我认为getDishes()循环中有一些东西。 This is how the docs go threw the data:这就是文档 go 抛出数据的方式:

FirebaseFirestore.instance
    .collection('users')
    .get()
    .then((QuerySnapshot querySnapshot) {
        querySnapshot.docs.forEach((doc) {
            print(doc["first_name"]);
        });
    });

Following the docs: https://firebase.flutter.dev/docs/firestore/usage Could you try to work with the forEach ?按照文档: https://firebase.flutter.dev/docs/firestore/usage你能尝试使用forEach吗?

I found the error, it was in getDishes method, the right one is:我发现了错误,它在 getDishes 方法中,正确的是:

Future<List<DishModel>> getDishes() async
  {
    DishModel dishTemp ;
    List<DishModel> dishes = [];
    _firestore.collection(collection).get().then((result) {
      for (DocumentSnapshot dish in result.docs) {
        dishTemp = DishModel.fromSnapshot(dish);
        List<IngredientModel> ing_temp = [];
        dish.reference.collection(subcollection).get().then((ingredientRes) {
          for(DocumentSnapshot ingredient in ingredientRes.docs) {
            ing_temp.add(IngredientModel.fromSnapshot(ingredient));

          }
          dishTemp.ingredients = ing_temp;
        });
        dishes.add(dishTemp);
      }
      return dishes;
    });
    return dishes;
  }

thanks to all谢谢大家

暂无
暂无

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

相关问题 从两个集合中获取数据,它是带有颤动的 firestore 中的子集合 - get data from both collection and it is sub collection in firestore with flutter 从 firestore 子集合检索快照到 dart/flutter 对象 - Retrieving snapshots from firestore sub-collection to dart/flutter object 如何使用 flutter 从 Firestore 获取子集合? - How do I fetch sub collection from firestore using flutter? 如何从 flutter 中的 Firestore 检索当前用户信息 - How to retrieve current user information from Firestore in flutter 无法从 Cloud firestore 中检索 Flutter 中的多个集合 - Cant Retrieve more than one collection in Flutter from cloud firestore 如何在Firestore中检索子集合的文档? - How to retrieve documents of a sub collection in Firestore? 如何从 flutter 中的文档中检索未知子集合 - how to retrieve unknown sub collection from document in flutter 如何将子集合转换为包含 flutter 和 firestore 的列表? - How to convert a sub collection to list with flutter and firestore? 如何从Cloud Firestore for Android一次提取所有集合和子集合的文档 - How to retrieve all the collection's and sub collection's document in a single fetch from cloud firestore for android 如何从保存在另一个集合中的 id 作为 flutter firestore 中的文档检索存储在一个集合中的文档 - How to retrieve documents stored in one collection from the ids saved in another collection as documents in flutter firestore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM