gpt4 book ai didi

flutter - Dart Map 增加一个键的值

转载 作者:IT王子 更新时间:2023-10-29 07:17:19 24 4
gpt4 key购买 nike

我目前正在使用一个 Map,其中的值是整数类型,但每次发生操作时我都需要更新键的值。示例:如果 map 是 { "key1": 1 } 在操作发生后它应该是 {"key1":2} 等等。这是我的代码:

void addToMap(Product product) {
if (_order.containsKey(product.name)) {
_order.update(product.name, (int) => _order[product.name]+1);
}
_order[product.name] = 1;
}

其中 _order 是 Map

最佳答案

您可以在 Dart 中使用以下惯用方法:

map.update(
key,
(value) => ++value,
ifAbsent: () => 1,
);

这使用了 built-in update 方法连同可选的ifAbsent帮助将初始值设置为 1 的参数本地图中没有 key 时。它不仅使意图明确,而且避免了像忘记放置在 other answer 中指出的 return 语句这样的陷阱。 .

此外,您还可以将上述方法封装为Extension。至 Map<dynamic, int> .这种方式还使调用站点看起来不那么困惑,如以下演示所示:

extension CustomUpdation on Map<dynamic, int> {
int increment(dynamic key) {
return update(key, (value) => ++value, ifAbsent: () => 1);
}
}

void main() {
final map = <String, int>{};
map.increment("foo");
map.increment("bar");
map.increment("foo");
print(map); // {foo: 2, bar: 1}
}

关于flutter - Dart Map 增加一个键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com