【问题标题】:Retrieve information from sub collection firestore + FLUTTER从子集合 firestore + FLUTTER 中检索信息
【发布时间】:2021-06-28 13:06:39
【问题描述】:

我是 Flutter 和 Firebase 的新手。

我有一个名为“dishes”的集合,其中有许多文档(例如名称、描述等),我还有一个称为成分的子集合,其中包含 id、名称和数量作为文档。

我正在尝试做的是检索所有带有食材的菜肴。

我有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];
  }
}

成分模型

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];

  }


}

料理助手

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

  }

}

菜品供应商

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

  DishProvider.initialize(){
    _loadDishes();
  }

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


}

主要是我写的

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

在家里(在构建方法中)

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

但如果我尝试打印 print(dishProvider.dishes); 我会得到 flutter: null 而不是颤振:Instance of 'DishModel'

如何解决并检索我的菜品信息?

谢谢大家

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore flutter-ios


    【解决方案1】:

    您需要获取菜品文档的 id 来检索子集合。

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

    Here 是一个 Github 仓库

    【讨论】:

    • 是的,我想我已经完成了这个:dish.reference.collection(subcollection).get()
    【解决方案2】:

    我认为getDishes() 循环中有一些东西。文档就是这样扔数据的:

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

    关注文档:https://firebase.flutter.dev/docs/firestore/usage 您可以尝试使用forEach 吗?

    【讨论】:

    • 但是通过这种方式,我只检索到了菜品文档,没有检索到与菜品相关的子集合“配料”
    【解决方案3】:

    我发现错误,在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;
      }
    
    

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2020-02-03
      • 2021-03-10
      • 2020-11-23
      • 2018-07-07
      相关资源
      最近更新 更多