Dart如何根据bool值判断是否向Map中添加指定键值对?
解决方案
你可以使用Dart内置的集合条件插入语法直接在Map字面量中完成条件判断,不需要拆分初始化和额外调用add方法,代码更简洁:
bool showJustify = false; final _valueToText = <Attribute, String>{ Attribute.leftAlignment: Attribute.leftAlignment.value!, Attribute.centerAlignment: Attribute.centerAlignment.value!, Attribute.rightAlignment: Attribute.rightAlignment.value!, if (showJustify) Attribute.justifyAlignment: Attribute.justifyAlignment.value!, };
说明
- 该语法在Dart 2.3及以上版本可用,同样支持List、Set的字面量初始化场景
- 布尔变量直接作为判断条件即可,不需要额外写
== true冗余判断 - 所有键值对的逻辑都集中在初始化语句中,后续维护更直观,不需要翻找后续的补充赋值逻辑
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

