【问题标题】:No data retrieved for specific collection Firebase未检索到特定集合 Firebase 的数据
【发布时间】:2021-05-09 23:18:39
【问题描述】:

我是 Flutter 的新手,我正在尝试构建一个送餐应用。 我设法使用提供商从 Firebase 加载类别,但完全相同的代码不适用于我的餐厅。 基本上,检索到的餐馆列表为空。它没有给我任何错误,仅此而已。

这是餐厅模型



class RestaurantModel{
  static const NAME = "name";
  static const ID = "id";
  static const AVG_PRICE = "avgPrice";
  static const RATING = "rating";
  static const RATES = "rates";
  static const IMAGE = "image";
  static const POPULAR = "popular";

  int _id;
  String _name;
  double _avgPrice;
  double _rating;
  String _image;
  bool _popular;
  int _rates;

  //GETTERS

  int get id => _id;
  String get name => _name;
  double get avgPrice => _avgPrice;
  double get rating => _rating;
  String get image => _image;
  bool get popular => _popular;
  int get rates => _rates;

  RestaurantModel.fromSnapshot(DocumentSnapshot snapshot){
    _id = snapshot.data()[ID];
    _name = snapshot.data()[NAME];
    _avgPrice = snapshot.data()[AVG_PRICE];
    _rating = snapshot.data()[RATING];
    _image = snapshot.data()[IMAGE];
    _popular = snapshot.data()[POPULAR];
    _rates = snapshot.data()[RATES];

  }

}

餐厅服务

    class RestaurantServices {

  String collection = "restaurants";
  FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future<List<RestaurantModel>> getRestaurants() async => _firestore.collection(collection).get().then((result){
    List<RestaurantModel> restaurants = [];
    for (DocumentSnapshot restaurant in result.docs) {
      restaurants.add(RestaurantModel.fromSnapshot(restaurant));
    }

    return restaurants;
  });



}

和餐厅供应商

class RestaurantProvider with ChangeNotifier{

  RestaurantServices _restaurantServices = RestaurantServices();
  List<RestaurantModel> restaurants = [];

  RestaurantProvider.initialize(){
    _loadRestaurants();
  }

  _loadRestaurants() async {

    restaurants = await _restaurantServices.getRestaurants();
    notifyListeners();

  }

}

【问题讨论】:

    标签: android firebase flutter flutter-animation


    【解决方案1】:

    Future 只返回 FutureOr,所以我们只需要等待并从下面的异步函数中获取值

     await _restaurantServices.getRestaurants().then((value){
          restaurants = value;
          notifyListeners();
        });
    

    希望它能帮助您实现您的要求。

    【讨论】:

    • 不,同样的问题,问题是,我在此之前阅读了另一个类别的集合,你认为这是问题吗?
    • 您能否在调用 notifyListeners 之前放置 print(restaurants) 并共享输出。这将有助于我更清楚地理解
    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 2016-12-02
    • 2018-12-09
    • 1970-01-01
    • 2021-01-03
    • 2017-11-21
    • 2018-05-29
    相关资源
    最近更新 更多