I am trying to create simple test, where if user clicks on the right answer, button background changes to green and stays green for 3 seconds.
I implemented set state with timer, but the background change is too instant still, hence timer is not working. Could you please share some thoughts on what could go wrong with that.
Here is my code
bool _buttonpressed = false;
void buttonPressed() {
setState(() {
if (_buttonpressed == false) {
_buttonpressed = true;
}
else if (_buttonpressed = true) {
_buttonpressed = false;
}
});
}
FilledButton(
onPressed: () {
setState(() {
Future.delayed(const Duration(seconds: 3), () {
setState(() {
_buttonpressed = !_buttonpressed;
});
});
});
},
style: ButtonStyle(
fixedSize: MaterialStateProperty.all(Size(320, 40)),
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) return Colors.red;
return Color(0XFFE4DBC8);
},
),
),
2
Answers
you can define a button like this:
and use it like this:
You can consider use
Timer
to achieve this feature.Below is the example code
In this code, the
clicked
flag immediately changed after button clicked, and set aTimer
that will change theclicked
flag 3 sec later