dictionary - 在 Dart 中使用 ifAbsent 映射更新方法

标签 dictionary flutter dart optional-parameters optional-arguments

我想修改 map 中的现有项,例如用新键替换现有键的值,如果键不存在于 map 中,则添加子句,以简单地创建一个新的键值对。 Dart 文档为此目的建议了更新方法,但我不太确定如何使用可选的 ifAbsent() 参数来实现它,我假设这是一行代码,如果要更新的 key 不存在则调用.

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

根据文档,有一个可选参数要采用,但它显示错误说参数太多,预期有 2 个,但找到了 3 个。

这显示没有错误(尚未测试,但理论上应该有效):

userData.update(key, value);

这(添加了 create if not exist 子句)可以:

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

非常感谢任何帮助获得后者或同等工作的帮助!我想我在这里遗漏了一些相当明显的东西......

最佳答案

这是一个命名参数,你可以这样使用它:

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

关于dictionary - 在 Dart 中使用 ifAbsent 映射更新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57037101/

相关文章:

c# - 将 Data 的 switch 语句重构为不同类型的数据

python - 列表理解以展平字典的字典

android - 将来使用 catchError 捕获错误并抛出另一种类型

performance - 使用在App开头加载的JSON配置文件还是在Flutter中使用具有静态/最终变量的类是更好的选择吗?

dart - Dart 中的 Web 组件

Swift:字典,删除为零的键和值

c# - 如何循环 Dictionary<IEnumerable<string>, Dictionary<IEnumerable<decimal>>?

android - Flutter WebView window.close()不起作用(Android)

dart - 如何在 flutter 中绘制一个扇区?

flutter - 如何在 Dart 中将数字格式化为千位分隔符