Home > other >  Dart: simpler way to find and adjust an Map inside the List
Dart: simpler way to find and adjust an Map inside the List

Time:02-15

I have user list and map like below

user = [
   {'user': 'John', 'id': 'aaa'},
   {'user': 'Jane', 'id': 'aa1'},
];

I want to find Jane and change her id as 'aa3'. Currently, I am searching the index inside the user[]. And then use that index to update the value of id.

   int i =  user.indexWhere((e) => e.name == 'Jane');
   user[i]['id'] = 'aa1';

Is there any way that I can do this at once? It seems very inefficient way to do it, but couldn't find the better way yet.

CodePudding user response:

It all really depends on how "performant" you need the solution to be. If I were you, I would first look at parsing that data into its own Person class. Let's have a look at an example:

@immutable
class Person {
  final String id;
  final String name;
  const Person({
    required this.id,
    required this.name,
  });

  @override
  bool operator ==(covariant Person other) => id == other.id;

  @override
  int get hashCode => id.hashCode;
}

Here I've overridden the == operator so that two Person instances that have the same id are considered to be equal. After you override this operator, you're recommended to override the hashCode getter as well and that is used for finding instances of your object inside a Map<T, E>.

Then I would place these Person instances inside a Map<String, Person> where the String keys inside the map would be IDs of the Person instances like so:

final persons = const {
  'aaa': Person(id: 'aaa', name: 'John'),
  'aa1': Person(id: 'aa1', name: 'Jane'),
};

After doing that, you can easily find your objects like this:

final aaa = persons['aaa'];
final aa1 = persons['aa1'];

CodePudding user response:

Travers through the list of users, simultaneously check for the respective user, when you will find one change its id and break from the loop.

try this :

  for(int i =0;i<user.length;i  )
  {
    var single_user=user[i];
    if(single_user['user']=='Jane'){
      single_user['id']="aa3";
      //or any changes as you want
      break;
    }
  }
  • Related