Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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.

like image 416
chichi Avatar asked Oct 23 '25 16:10

chichi


1 Answers

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'];
like image 117
Vandad Nahavandipoor Avatar answered Oct 26 '25 05:10

Vandad Nahavandipoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!