Search code examples
flutterstatestatefulwidget

How to prevent multiple StatefulWidgets (ImageSliders) from overriding each others contents?


So I am trying to place three ImageSliders on the same page/card. They are quite similar which is why I created one class and just wanted to pass changing values over.

That didn't really work as intended: now there is just three times the last called slider.

I figured it's prbly the same state which is being overwritten and tried to pass a unique key.

Didn't change a thing though.

The slider:

List<String> _imgList;
List<String> _nameList;
String _description;

class ShopListSlider extends StatefulWidget {
  ShopListSlider(
      {Key key,
      String description,
      @required List<String> imgList,
      @required List<String> nameList})
      : super(key: key) {
    _imgList = imgList;
    _nameList = nameList;
    _description = description;
  }

  @override
  _ShopListSliderState createState() => _ShopListSliderState();
}

class _ShopListSliderState extends State<ShopListSlider> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(...);
 }
}

Content of the widget calling the slider(s):

child: Column(children: [
          SizedBox(height: 50),
          ShopListSlider(
              key: UniqueKey(),
              description: "Restaurants in Deiner Nähe",
              imgList: imgListNear,
              nameList: nameListNear),
          SizedBox(height: 50),
          ShopListSlider(
              key: UniqueKey(),
              description: "Beliebte Restaurants",
              imgList: imgListBest,
              nameList: nameListBest),
          SizedBox(height: 50),
          ShopListSlider(
              key: UniqueKey(),
              description: "Deine Favoriten",
              imgList: imgListFavorites,
              nameList: nameListFavorites),
        ]),

Solution

  • This will work fine without any keys.

    The problem is your class vars are not inside the class, they're package level, which basically means all the widgets are stateless, sharing some global state.

    Just move these own inside the State, and remove those keys:

    class _ShopListSliderState extends State<ShopListSlider> {
       List<String> _imgList;
       List<String> _nameList;
       String _description;
    

    Fwiw, tossing a UniqueKey() like that will force a rebuild of a widget everysingle build(), whether it's changed or not, which is not really what you want.