简体   繁体   English

在 Dart 中使用 ifAbsent 的地图更新方法

[英]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. Dart 文档为此目的建议了更新方法,但我不太确定如何使用可选的 ifAbsent() 参数来实现它,我假设这是一行代码,如果要更新的密钥不存在.

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.根据文档,有一个可选参数要采用,但它显示一个错误,说参数太多,需要 2 个,但找到 3 个。

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:这(添加了 create if not exist 子句)执行以下操作:

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

Updates the value for the given key.更新给定键的值。

user["age"] = 25;
user.update("age", (dynamic val) => ++val); // => 26

This also returns the new value.这也会返回新值。 To prevent an error being thrown should the key not exist, there's a third parameter:为了防止在键不存在时抛出错误,还有第三个参数:

user.update("name", (dynamic val) => "Jim", ifAbsent: () => "Jane");
print(user); // => {"age": 26, "name": "Jane"};

In most cases you could update using the array bracket notation:在大多数情况下,您可以使用数组括号表示法进行更新:

user["name"] = "Mary";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM