Reputation: 2679
I have a collection of 12 images that I want to display on the screen as the user presses its respective toggle button.
For simplicity, I'll say that I have 3 images:
img.Image image1 = img.decodeImage(_imageFile.readAsBytesSync());
img.Image image2 = img.decodeImage(_imageFile2.readAsBytesSync());
img.Image image3 = img.decodeImage(_imageFile3.readAsBytesSync());
List<bool> isSelected = [true, false, false];
//only showing relevant portion of @build function
ToggleButtons(
color: Colors.teal,
selectedColor: Colors.blueGrey,
children: [
Icon(Icons.accessibility),
Icon(Icons.pets),
Icon(Icons.phone),
],
isSelected: isSelected,
onPressed: (index){
setState(() {
isSelected[index] = !isSelected[index];
print(isSelected);
});
},
),
Based on what buttons the user presses I want to display that image. I dont want to write if-else statements for all possible combinations of the isSelected
, and based on the isSelected
list I would display the image, for example in its default state of [true, false, false]
only image1
should be displayed.
How would I get all possible combinations of isSelected
? For this purpose I found the trotter library: https://pub.dev/packages/trotter, but apparently it does not accept list of bool.
After I am able to get all possible combinations of my list that how do I map, each image to its respective toggle button?
Upvotes: 1
Views: 182
Reputation: 518
You can use a ListView.builder
here.
Store the images in an array like List<Image> images = [image1, image2, image3,...]
.
The code will look something like the following:
ListView.builder(
itemCount: isSelected.length,
itemBuilder: (context, index) {
// Only render the image if it is selected.
return isSelected[index] ? images[index] : Container();
},
);
It would be best if you abstract this away by making a class (since there is an isSelected and Image for every ListImage
let's call it.
If you have any further questions, please don't hesitate to leave a comment. Thanks :)
Upvotes: 1