skip to Main Content

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

2

Answers


  1. 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'],);
    
    Login or Signup to reply.
  2. 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'],);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search