Swaroop Maddu
Swaroop Maddu

Reputation: 4884

How to update Map Value in Flutter Firebase Firestore

I have a Map object in my document data. Like Below

enter image description here

I have to add a new user bid to the same map without erasing old data but the code I used was replacing the whole Map with the new value. Any suggestions on how to achieve my goal.

FirebaseFirestore.instance.collection('products')
.doc(widget.product.uid).update({
  'bids': {
  auth.currentUser?.email:
      currentPrice.toString()
  }
});

Upvotes: 2

Views: 2711

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50930

You need to use dot notation to update a nested field:

const userEmail = auth.currentUser?.email;
FirebaseFirestore.instance.collection('products')
.doc(widget.product.uid).update({
  'bids.${userEmail}':  currentPrice.toString()
});

Dot notation allows you to update a single nested field without overwriting other nested field. If you update a nested field without dot notation, you will overwrite the entire map field

References:

  1. Update fields in nested objects
  2. FlutterFire Documentation

To update fields with . in their keys:

var fPath = FieldPath(["bids", "[email protected]"]);
FirebaseFirestore.instance.collection('products').doc(widget.product.uid).update(fPath, currentPrice.toString());

Upvotes: 8

Related Questions