Home > OS >  Is it possible to add or remove to a list based on a bool value?
Is it possible to add or remove to a list based on a bool value?

Time:11-15

I have the following bool

bool showJustify = false;

and I have the following list:

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

What I'd like to do is only add the final Attribute.justifyAlignment: Attribute.justifyAlignment.value! only if showJustify = true

Is there a simply way to accomplish this?

I was thinking of only adding the first 3 to the original list and then doing

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

But maybe there is a simpler way?

CodePudding user response:

Yes, you can do that using collection-if. For example:

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

To answer your question:

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!,
};

CodePudding user response:

You can include the elements in a list in another list with ... and since you can add a ternary condition to it, you can add those elements with the condition. Then you can generate the map from the list using Map::fromIterable. Like so:

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