Reputation: 2128
I have a flow like this.
initState
).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.
Upvotes: 0
Views: 663
Reputation: 5423
You need to make these changes.
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_start = 10;
});
_startTimer();
},
child: Icon(Icons.add),
)
and
void _startTimer() {
const oneSec = Duration(seconds: 1);
_timer = Timer.periodic(
oneSec,
(_) {
if (_start == 0) {
setState(() {
_timer.cancel();
});
} else {
setState(() {
_start--;
});
}
},
);
}
Upvotes: 2
Reputation: 929
that's because your _start variable is 0 you need to set it to 10 again then call startTimer
Upvotes: 0