flutterstateflutter-listviewanimatedcontainer

Set state separately for each ListView element. Flutter


Every element of my ListView is AnimatedContainer

AnimatedContainer(
height: _height,
...)

While changing _height via setState it works for every ListView element of course.

    Future<void> _changeHeight() async {
     setState(() {
      _height = 2;
    });}

How to set _height separately for each element AnimatedContainer?


Solution

  • instead of a _height variable of type double, use a key/value map with the keys as the list item's index and the value as its height

    Map<int, double> heights = {};
    

    To use the height:

    AnimatedContainer(
       height: heights[index]!,
       //...
    )
    

    And to set the height:

    Future<void> _changeHeight() async {
      setState(() {
        heights[index] = 2;
      });
    }