Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Update method with ifAbsent in Dart

I'd like to modify an existing item in a map, as in replace the value of an existing key with a new one, with an added clause if the key does not exist in the Map already, to simply create a new key and value pair. The Dart documentation suggests the update method for such a purpose, but I'm not quite sure about how to implement it with the optional ifAbsent() parameter, which I assume is a line of code called if the key to be updated does not exist.

V update(K key, V update(V value), {V ifAbsent()});

According to the documentation, there is an optional parameter to be taken, but it shows an error saying too many parameters, 2 expected but 3 found.

This shows no error (not yet tested, but theoretically should work):

userData.update(key, value);

This (with the added create if not exist clause) does:

userData.update(key, value,
  userData[key] = value;
  );

Any help to get the latter or equivalent to work is much appreciated! I assume I'm missing something rather obvious here...

like image 227
Terrornado Avatar asked Jul 15 '19 09:07

Terrornado


People also ask

What is map () in Dart?

Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times.


1 Answers

That is a named parameter, you can use it like this:

userData.update(
  key, 
  // You can ignore the incoming parameter if you want to always update the value even if it is already in the map
  (existingValue) => value, 
  ifAbsent: () => value,
);
like image 72
Martyns Avatar answered Oct 30 '22 19:10

Martyns