You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:45:03