I am having trouble adding random images to the page by using a floating action button. After drawing an image from the .shuffle list, I want to draw another picture from the list. I could add more pictures with the action button, but when pressing the floating action button, it also changed the previous image. As a result, even if I can shuffle the images, I can only get the result of showing a large amount of the same image instead of adding a different image.
List stickerList = [];
void addNewImageToList () {
setState(() {
stickerList.add(Container(
width: 250,
height: 250,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'lib/images/${assetsList[stickerList.length]}'),
fit: BoxFit.fill,),
borderRadius: BorderRadius.circular(50)
));
});
}
body: ListView.builder(
itemCount: stickerList.length,
itemBuilder: (context, index) {
return Column(
children: [Container(
width: 250,
height: 250,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'lib/images/${assetsList[stickerList.length]}'),
fit: BoxFit.fill,),
borderRadius: BorderRadius.circular(50))
)],
);
},),
floatingActionButton:FloatingActionButton(
onPressed: () {
addNewImageToList();},
heroTag: Icons.group_add,
child: Icon(Icons.group_add),)
I would like to ask how can I modify it and add a new image from shuffle list every time without affect the previously added image?
What logic direction should I go for?
Like, disconnecting the previous image with the action button?
Generating a shuffle list and call the image accordingly with ascending order without shuffling it every time?
I am not quite sure which direction is valid as I am not quite familiar with coding.
Thank you.
2
Answers
you can get a random index within the range of the assetsList length using
Random().nextInt()
. Then, you can add a new image to stickerList based on the randomly selected indexhere is the code what i have done:
The problem is this line in your ListViewBuild code.
Whilst your builder function will iterate, each iteration will always have the same value of
stickerList.length
.The following should be a bit closer to what you need.