Note: One can go according to @Amit Prajapati 's solution/logic, but if
your use-case is going to get complex over time then I would recommend
going as per the below solution.
Whenever you need to change the property of a specific element from a list of elements, use a list of values having the same datatype as that of the value accepted by that property having the same length as that of the number of elements in your main list.
In your case you need to change the color of a specific ListTile whenever the user clicks on it. So declare a List of Colors.
List<Color> tileColors;
Now in initState() of your main widget initialize the List with its default values (depending on the length of our main widget).
for(int i=0;i<items.length;i++) tileColors.add(defaultColor);
Now while using a builder function set each item(ListTile) of your list with tileColors[index],
(I'll be using ListView.builder)
ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
color: tileColors[index],
child: ListTile([...]),
);
}
)
Now just setState() the value of the property(color) of that ListTile whenever the user taps on it.
ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
color: tileColors[index],
child: ListTile(
onTap: (){
setState((){
for(int i=0;i<item.length;i++) tileColors[i] = defaultColor;
tileColors[index] = selectedColor; // selectedColor is the color which you wish to change to.
// Note: You can add your own conditions over. e.g. If you want the first tile to be of a specific color and the rest should be different color while the user taps.
});
}
),
);
}
)
Tip: You can use AnimatedContainer instead of Container widget to create a
smooth transition when the user taps. Set the duration
parameter to Duration(milliseconds: 300)
.