是否可以根据布尔值添加或删除列表



我有以下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!,
};

我想做的是只在showJustify = true的情况下添加最终的Attribute.justifyAlignment: Attribute.justifyAlignment.value!

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

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

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

但也许还有一个更简单的方法?

是的,您可以使用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!,
};

您可以使用...将列表中的元素包括在另一个列表中,因为您可以向其中添加三元条件,所以您可以使用该条件添加这些元素。然后,您可以使用Map::fromIterable从列表中生成地图。像这样:

final _valueToText = Map.fromIterable<Attribute, String>([
Attribute.leftAlignment, 
Attribute.centerAlignment, 
Attribute.rightAlignment, 
...(showJustify
? 
[Attribute.justifyAlignment] : []
),
], 
key: (attr) => attr, 
value: (attr) => attr.value!
);

最新更新