LonelyWolf
LonelyWolf

Reputation: 4392

Get index of first true value in list of bool

     ListView(
    physics: NeverScrollableScrollPhysics(),
    children: <Widget>[
      ToolControlButton(
        onPressed: () => onControlPress(0),
        isSelected: selectedControl[0],
        icon: Icons.category,
        text: 'Option1',
      ),
      ToolControlButton(
        onPressed: () => onControlPress(1),
        isSelected: selectedControl[1],
        icon: Icons.category,
        text: 'Option2',
      ),
      ToolControlButton(
        onPressed: () => onControlPress(2),
        isSelected: selectedControl[2],
        icon: Icons.category,
        text: 'Option3',
      ),
      ToolControlButton(
        onPressed: () => onControlPress(3),
        isSelected: selectedControl[3],
        icon: Icons.category,
        text: 'Option4',
      )
    ],
  )

I've got List of Booleans

List<bool> selectedControl = [true, false, false, false];

And list of Widgets

List<Widget> cont = [
Container(color: Colors.red),
Container(color: Colors.green,
Container(color: Colors.orange),
Container(color: Colors.blue)
];

I want to display cont widget at the index where selectedControl has true value. This is what I managed to do so far and it works. Is there any better way of doing it for this purpose?

return cont[selectedControl.indexWhere((selected) => selected == true)],

Upvotes: 2

Views: 2068

Answers (1)

Shababb Karim
Shababb Karim

Reputation: 3733

return cont[selectedControl.indexWhere((selected) => selected == true)];

This will work because this is just the opposite of firstWhere where the first element which satisfies the condition is met. indexWhere is the equivalent of firstWhere but it only returns an index of the first met condition. However, If none selected is true then indexWhere returns -1 and that will cause an out of bounds exception.

You could write your code like this:

final selectedControlIndex = selectedControl.indexWhere((selected) => selected);
return selectedControlIndex >= 0? cont[selectedControlIndex] : Container();

Upvotes: 2

Related Questions