i want to change the color and trail icon after i click. the problem is the icon and thrail doesn’t change after i click the index. this is my code :
Widget _builduserlist(BuildContext context, List<postmodel> model) {
List<bool> itemTappedState = List.generate(model.length, (index) => false);
return Center(
child: ListView.builder(
itemCount: model.length,
itemBuilder: (context, index) {
return Card(
color: itemTappedState[index]
? Colors.blue // Change the color when tapped
: Colors.green,
child: ListTile(
title: Text('${model[index].id}'),
subtitle: Text('${model[index].dateofinsp}'),
leading: const Icon(Icons.edit_road),
trailing: itemTappedState[index]
? const Icon(Icons.check)
: const Icon(Icons.warning), // Change the trailing icon when tapped
onTap: () {
print(itemTappedState[index].toString());
setState(() {
itemTappedState[index] = !itemTappedState[index];
print(itemTappedState[index].toString());
});
_showConfirmationDialog(context, model[index]);
},
),
);
},
),
);
}
i have print the bool before setState() and in SetState(). it changes in the setState() but
not the index. how do i solve this problem
2
Answers
The problem is that your
itemTappedState
is declared within your_builduserlist
method:And the
_builduserlist
method re-runs everysetState
. SoitemTappedState
will be reset to the value you set it every time you update the UI.To solve the problem, move the
itemTappedState
in the State class:setState
works inside theState
of aStatefulWidget
. So you should make your user list widget like this instead:Note: Put this code at top-level (outside any other class)