Ali Hazem
Ali Hazem

Reputation: 89

How to update Map's key with new value if the key exists?

I have a todoDate (Map<String, List> variable), and I add a key but sometimes the key already exists therefore nothing is added to the Map data type I want to add the value to the existing key but doesn't work.
I have 2 textfields (each one has a controller) and a button: addKey() functionality in the button's onPressed.

void addKey()
{
  for (var key in todoDate.keys) {
    final containsKey = todoDate.containsKey(key);
    
    if (containsKey) {
      todoDate.update(key, (value) =&gt; todoDate[key] = value);
    } else {
      // if key doesn't exist, create new key and value
      setState(() { todoDate[dateController.text.toTitleCase()] = [ taskController.text.toTitleCase() ]; });
    }
  }
}

However it doesn't work, I think the I wrote the update method wrong so how do I do that correct?

Upvotes: 1

Views: 797

Answers (1)

HKN
HKN

Reputation: 364

update function already has a parameter called ifAbsent. So what you need is just passing the new value to the update and to the ifAbsent. your function would look like this:

void addKey(key,newValue) {
    todoDate.update(key, (value) => newValue,ifAbsent: () => newValue);
}

Upvotes: 3

Related Questions