我想修改 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/