Home > Mobile >  I am facing following error "The method '[]' can't be unconditionally invoked be
I am facing following error "The method '[]' can't be unconditionally invoked be

Time:12-14

hi i am new flutter development and i'm facing error:

The method '[]' can't be unconditionally invoked because the receiver can be 'null'

in following lines image:

element.data()['image'],
name: element.data()['name'],
price: element.data()['price']

please let me know if there is any solution

List<FoodCategoriesModle> burgerCategoriesList = [];
   Future<void> getBurgerCategoriesList() async {
   List<FoodCategoriesModle> newBurgerCategoriesList = [];
   QuerySnapshot querySnapshot = await FirebaseFirestore.instance
    .collection('foodcategories')
    .doc('8Dtfnhwbi1cDkCrX02rA')
    .collection('burger')
    .get();
    querySnapshot.docs.forEach((element) {
    FoodCategoriesModle burgerCategoriesModle = FoodCategoriesModle(
    image: element.data()['image'],
    name: element.data()['name'],
    price: element.data()['price'],);
    newBurgerCategoriesList.add(burgerCategoriesModle);
    burgerCategoriesList = newBurgerCategoriesList;
    });
  }

CodePudding user response:

change those:

    image: element.data()['image'],
    name: element.data()['name'],
    price: element.data()['price'],);

with this:

    image: (element.data() as Map<String, dynamic>)!['image'],
    name: (element.data() as Map<String, dynamic>)!['name'],
    price: (element.data() as Map<String, dynamic>)!['price'],);

CodePudding user response:

Your element.data() you looking for may be null you need set default value for them like this:

image: (element.data() ?? {})['image'],
name: (element.data()?? {})['name'],
price: (element.data()?? {})['price'],);
  • Related