Home > database >  Flutter: find item in list of maps and update it
Flutter: find item in list of maps and update it

Time:09-13

I have 3 nested collections (portfolios, rents and leases) and I get the last one like this:

getRentLeases() {
    final portfolio = list.where((portfolio) {
      return portfolio['documentID'].contains(currentPortfolioId)
          ? true
          : false;
    }).toList();
    final rent = portfolio[0]['rents'].where((rent) {
      return rent['documentID'].contains(currentRentId) ? true : false;
    }).toList();
    return rent[0]['leases'];
  }

as you see I always have the ID for previous collection saved.

To find a specific lease I could follow similar approach:

var lease = getRentLeases().where((lease) {
      return lease['documentID'].contains(newLease['documentID'])
          ? true
          : false;
    }).toList();

but how could I update it? Something like this doesn't work:

lease = newLease;

CodePudding user response:

  1. ? true : false is not necessary as contains already gives you a boolean value.
  2. If you only expect one item to be returned by the where method, then you should go for singleWhere as it directly gives you the item instead of the list. If none of these or multiple items satisfy the condition, you get an exception.
  3. You should separate getRentLeases into two methods. In this case its even better to have methods returning the index of the relevant item. Please consider that I only used dynamic because I don't have access to the data types. You should instead type the variables.

Code:

int getIndexOfPortFolio(String portfolioId) {
  return list
  .indexWhere(portfolio => portfolio['documentID'].contains(portfolioId));
}

int getIndexOfRent(dynamic portfolio, String rentId) {
  return portfolio['rents']
  .indexWhere(rent => rent['documentID'].toString().contains(rentId));
}

int getIndexOfLease(dynamic rent, String leaseId) {
  return rent['leases']
  .indexWhere(lease => lease['documentID'].toString().contains(leaseId));
}

And then you can update your object like this:

void updateLease(String portfolioId, String rentId, String oldLeaseId, dynamic newLease) {
  int portFolioIndex = getIndexOfPortFolio(portfolioId);
  var portFolio = list[portFolioIndex];
  int rentIndex = getIndexOfRent(portFolio, rentId);
  var rent = portFolio["rents"][rentIndex];
  int leaseIndex = getIndexOfLease(rent, oldLeaseId);
  rent["leases"][leaseIndex] = newLease;
}
  • Related