首页 > 解决方案 > 是否可以根据布尔值添加或删除列表?

问题描述

我有以下bool

bool showJustify = false;

我有以下列表:

    final _valueToText = <Attribute, String>{
      Attribute.leftAlignment: Attribute.leftAlignment.value!,
      Attribute.centerAlignment: Attribute.centerAlignment.value!,
      Attribute.rightAlignment: Attribute.rightAlignment.value!,
      Attribute.justifyAlignment: Attribute.justifyAlignment.value!,
    };

我想做的只是仅在以下情况下才添加Attribute.justifyAlignment: Attribute.justifyAlignment.value!决赛showJustify = true

有没有一种简单的方法可以做到这一点?

我想只将前 3 个添加到原始列表中,然后执行

if (showJustify == true)
_valueToText.add(Attribute.justifyAlignment: Attribute.justifyAlignment.value!) 

但也许有更简单的方法?

标签: flutterdart

解决方案


是的,您可以使用collection-if来做到这一点。例如:

bool condition = true/false;
final map = <int, String>{
  0: 'Zero',
  if (condition) 1: 'One',
};

要回答您的问题:

final _valueToText = <Attribute, String>{
 Attribute.leftAlignment: Attribute.leftAlignment.value!,
 Attribute.centerAlignment: Attribute.centerAlignment.value!,
 Attribute.rightAlignment: Attribute.rightAlignment.value!,
 if (showJustifty) Attribute.justifyAlignment: Attribute.justifyAlignment.value!,
};

推荐阅读