1

I'm using Flutter, I want to to find all the products in a given snapshot and then return a list of products from a snapshot. But it there is an error says "The method '[]' can't be unconditionally invoked because the receiver can be 'null'."

Source Code

// product list from snapshot
  List<Product> _productListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
      return Product(
        id: doc.id,
        name: doc.data()['name'] ?? '',
        price: doc.data()['price'].toDouble() ?? '',
        description: doc.data()['description'] ?? '',
        imageUrls: doc.data()['imageUrls'] ?? '',
      );
    }).toList();
  }

Screenshot

code screenshot

D. Rohan
  • 23
  • 4

1 Answers1

1

Only cast the values with dynamic:

// product list from snapshot
  List<Product> _productListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
      return Product(
        id: doc.id,
        name: (doc.data() as dynamic)['name'] ?? '',
        price: (doc.data() as dynamic)['price'].toDouble() ?? '',
        description: (doc.data() as dynamic)['description'] ?? '',
        imageUrls: (doc.data() as dynamic)['imageUrls'] ?? '',
      );
    }).toList();
  }
Hassan Ali
  • 125
  • 3