No data retrieved for specific collection Firebase

Issue

I am new to Flutter and I am trying to build a food delivery app.
I managed to load the categories from Firebase using a provider, but the exact same code wont work for my restaurants.
Basically, the list of restaurants retrieved is null. It gives me no errors, just that.

this is Restaurant Model



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

  }

}

Restaurant services

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



}

And Restaurant Provider

class RestaurantProvider with ChangeNotifier{

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

  RestaurantProvider.initialize(){
    _loadRestaurants();
  }

  _loadRestaurants() async {

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

  }

}

Solution

Future<List> is return only the FutureOr so we only need to wait and get the value from the async function like below

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

I hope it will help you to achieve your requirement.

Answered By – Balasubramani Sundaram

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.