How to fill Map from DocumentSnapshot in Using Firestore in Flutter?

Viewed 38

I am trying to fill up a Map from DocumentSnapshot in a Flutter.

but I'm having a syntax error within the code. This is the code I'm trying to work with:


 Future<Map<String, dynamic>> particularItem(String productId) async {
      DocumentSnapshot prodRef = await _productReference.doc(productId).get();
      Map<String, dynamic> itemDetail = new Map();
      itemDetail['image'] = await getProductsImage(prodRef.data()['imageId'][0]);
      itemDetail['color'] = prodRef.data()['color'];
      itemDetail['size'] = prodRef.data()['size'];
      itemDetail['price'] = prodRef.data()['price'];
      itemDetail['name'] = prodRef.data()['name'];
      itemDetail['productId'] = productId;
      return itemDetail;
    }

And this is the error I'm getting in the below snippet:

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.

prodRef.data()['imageId']
prodRef.data()['color']
prodRef.data()['size']
prodRef.data()['price']
prodRef.data()['name']
1 Answers

You should cast prodRef.data() before use it. In dart object can't not use the operator []

final data = prodRef.data() as Map<String, dynamic>;

Then you can get property from data variable. For more, you can read here Firebase documentation

Related