I created a new Button Class. This button has a Timer, which is normally gray and changes color after 5 seconds. When tapped, it turns gray again and changes color after 5 seconds. I want to reset the counter (_counter=0) to change the color, but I don't know how to do it. This is my code.
class NewFloatingButton extends StatefulWidget {
final VoidCallback onTap;
NewFloatingButton(this.onTap);
@override
State<NewFloatingButton> createState() => _NewFloatingButtonState();
}
class _NewFloatingButtonState extends State<NewFloatingButton> {
int _counter = 0;
late Timer timer;
dynamic buttonColor() {
if (_counter < 6) {
return Colors.grey;
} else{
return Colors.purple;
}
}
@override
void initState() {
super.initState();
timer = Timer.periodic(
const Duration(seconds: 1),
(Timer timer) {
_counter ;
setState(() {});
},
);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
child: Container(
height: 50,
width: 50,
decoration: BoxDecoration(
color: buttonColor(),
borderRadius: BorderRadius.circular(28),
boxShadow: const [
BoxShadow(
spreadRadius: 2,
blurRadius: 2,
color: Colors.black12,
offset: Offset(1, 1))
],
),
alignment: Alignment.center,
child: const Icon(
Icons.arrow_forward,
color: Colors.white,
),
),
);
}
}
Where should I put "_counter=0"?
CodePudding user response:
You can update your GestureDetector onTap to look something like this:
@override
Widget build(BuildContext context) {
return GestureDetector(
// Add this
onTap: (){
widget.onTap();
setState((){
_counter=0;
});
},
child: Container(
height: 50,
width: 50,
decoration: BoxDecoration(
color: buttonColor(),
borderRadius: BorderRadius.circular(28),
boxShadow: const [
BoxShadow(
spreadRadius: 2,
blurRadius: 2,
color: Colors.black12,
offset: Offset(1, 1))
],
),
alignment: Alignment.center,
child: const Icon(
Icons.arrow_forward,
color: Colors.white,
),
),
);
}
CodePudding user response:
You can add
onTapUp: (details) {
setState(() {
_counter = 0;
});
},