'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 1:[1]
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;
});
}
Solution 2:[2]
You are assigning a single variable to all the list elements as it's height! So, if you change it, all of them will be changed, beacause they are actually a single variable. The solution is one of these:
- Define a list of doubles or a map that includes the height of every element seperately.
- Use an invisible container for the rest of your item, and a list of booleans, when the item is tapped, set state corresponding boolean to true, and change the visibility of that invisible container.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roaa |
| Solution 2 | Parsa Dany |
