Does anybody knows why this piece of code its not working corretly? The color it's not changing when I tap.
It might be a simple question, but I'm not an expert, I'm still learning.
var CardColor = Colors.blue;
void changeColor() {
CardColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
}
Widget BuildMainListView() {
return ListView(children: [
for (int index = 0; index < 25; index )
Card(
color: CardColor,
child: ListTile(
title: Text(
'Item Número $index',
textScaleFactor: 1.2,
),
subtitle: Text('Este é o item de númer $index'),
trailing: Icon(Icons.star),
onTap: () => changeColor,
))
]);
}
The function does not work, I tried without a functiont too, same result.
CodePudding user response:
First, make sure you're using StatefulWidget
, Then you will need to update the state with setState
when changing cardColor
:
void changeColor() {
CardColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
setState(() {}); // add this
}
finally, assign the method directly to onTap
, like this:
Widget BuildMainListView() {
return ListView(children: [
for (int index = 0; index < 25; index )
Card(
color: CardColor,
child: ListTile(
title: Text(
'Item Número $index',
textScaleFactor: 1.2,
),
subtitle: Text('Este é o item de númer $index'),
trailing: Icon(Icons.star),
onTap: changeColor, // remove () =>
))
]);
}