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...
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,
);