So I have a listview.builder in Flutter. It returns an InkWell that has a Card in Container as a child. The container has a color that has to change when the card is tapped. I want to do this with setState()
but it won't work. It doesn't seem to work to set state inside a listview. How do I make the cards dynamic????
Container(
margin: EdgeInsets.only(top: 10),
height: 200,
color: Colors.cyan,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 3,
itemBuilder: (context, index) {
var mycolor=Colors.white;
return InkWell(
onTap: () {
setState(() {
if (mycolor == Colors.white) {
mycolor=Colors.grey[300];
} else {
mycolor=Colors.white;
}
});
},
child: Card(
color: mycolor,
child: Container(
width: 100,
height: 100,
),
),
);
}
),
),
Solution 1: Rodolfo Franco
I would recommend declaring the mycolor
variable in the widget state at the beginning like this:
Color mycolor = Colors.white;
Then on your onTap function you could do something like this:
if (mycolor === Colors.white) {
setState(() {
mycolor = Colors.grey[300];
}
} else {
setState(() {
mycolor = Colors.white;
}
}
Solution 2: Aaron Saunders
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// list of colors to map to specific index of list items
List<Color> _color = [
Colors.green[400],
Colors.green[400],
Colors.green[400]
];
// when tapped, toggle the color
void _toggleColor(_index) {
setState(() {
if (_color[_index] == Colors.white) {
_color[_index] = Colors.green[400];
} else {
_color[_index] = Colors.white;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 3,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
return this._toggleColor(index);
},
child: Card(
color: this._color[index], // get value from state object
child: Container(width: 100, height: 100)));
}),
);
}
}