Home > Back-end >  how can I solve this problem after shuffling a list?
how can I solve this problem after shuffling a list?

Time:10-21

I have a list of objects and I would like to show them in a random order every time I open the app. this is the code:

final placesInCity = availablePlaces.where((city) {
  return city.cityId.contains(categoryId);
}).toList().shuffle();

//here I added the shuffle

return Scaffold(
  appBar: AppBar(
    title: Text(categoryTitle!),
  ),
  body: ListView.builder(
    itemCount: placesInCity.length,
    itemBuilder: (context, index) {
      return PlaceItem(
        id: placesInCity[index].id,
        title: placesInCity[index].title,
        imageUrl: placesInCity[index].imageUrl,
        food: placesInCity[index].food,
        compass: placesInCity[index].compass,
        transportation: placesInCity[index].transportation,
      );
},

after I added the shuffle() all of the index turned red

CodePudding user response:

shuffle works in-place - it doesn't return a new shuffled list, but rather shuffles the existing one and returns void. The problem here is that you are assigning the result of shuffle to a variable.

final placesInCity = availablePlaces.where((city) {
  return city.cityId.contains(categoryId);
}).toList();
placessInCity.shuffle();
  • Related