I have a flow like this.
- When the screen is open, the timer is started (I drop the timer function on
initState
).
- After the timer is finished, I want to re-countdown the timer again. I try call the timer function on
initState
in the onPressed
but the timer not re-countdown again.
This is my code:
class _MyHomePageState extends State<MyHomePage> {
Timer _timer;
int _start = 10;
void _startTimer() {
const oneSec = Duration(seconds: 1);
_timer = Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
setState(() {
timer.cancel();
});
} else {
setState(() {
_start--;
});
}
},
);
}
@override
void initState() {
super.initState();
_startTimer();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Timer:',
),
Text(
'$_start',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _startTimer,
child: Icon(Icons.add),
),
);
}
}
I already googling with keyword re-countdown timer in Flutter
but didn't find solution.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…