简体   繁体   中英

How to update particular variable of particular data in List<Map<String,dynamic>> in firebase using flutter?

I have customer collection inside I have list of merchant data like

{
  'customer':'xyz',
  'contactNumber':'999999999',
  'merchantMap':[
       {
        'merchantName':'abx',
        'merchantId':'dsdfsbdmmm'
       },
       {'merchantName':'abx',
        'merchantId':'dsdfsbdmmm'
       }
  ]
}

Here inside merchantMap I want to update his name by checking his merchantId. How can I achieve this?

Lets assume your customer data is this:

var customerData = {
    'customer': 'xyz',
    'contactNumber': '999999999',
    'merchantMap': [
      {'merchantName': 'abx', 'merchantId': '12'},
      {'merchantName': 'abx', 'merchantId': '23'}
    ]
  };

and your specific id is this:

String selectedId = "23";

you can do this to change the item that contains that id:

var newMerchantMap =
    (customerData["merchantMap"] as List<Map<String, dynamic>>)
        .map((e) => e['merchantId'] == selectedId
            ? {'merchantName': 'newNAme', 'merchantId': e["merchantId"]}
            : e)
        .toList();

customerData['merchantMap'] = newMerchantMap;

result:

{
   customer: xyz,
   contactNumber: 999999999, 
   merchantMap: [
       {merchantName: abx, merchantId: 12},
       {merchantName: newNAme, merchantId: 23}
   ]
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM