Reputation: 21
I am using the countdown_flutter component to count down. When starting it is working normal. however, I would like to restart the counter (call the component again) so that the countdown starts again when I press a button or another action:
my code:
_buildCount() {
return Expanded(
child: Container(
child: Center(
child: CountdownFormatted(
duration: Duration(seconds: 15),
onFinish: () {
_controller.nextQuestion();
print('finished!');
},
builder: (BuildContext ctx, String remaining) {
return Text(
remaining,
style: TextStyle(fontSize: 20),
); // 01:00:00
},
),
),
),
);
}
onNext: () {
setState(() {
_scoreKeeper.add(
Icon(
correct ? Icons.check : Icons.close,
color: correct ? Colors.green : Colors.red,
),
);
if (_scoreKeeper.length < _controller.number) {
_buildCount(); // I would like to recall him here
_controller.nextQuestion();
} else {
_stopWatch.stop();
FinishDialog.show(
context,
usuarioLogado: usuarioLogado,
);
}
});
},
Upvotes: 0
Views: 312
Reputation: 180
I use in my quiz game also a countdown and i realize it like the following code example.
For the first time you can set the countdown value in the initState method and then you can write a resetTimer() function to reset the countdown. This function can you call in onPressed by a RaisedButton or whatever you want. Don't forget to cancel the timer with the cancel() function.
import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(TimerExample());
class TimerExample extends StatefulWidget {
@override
_TimerExampleState createState() => _TimerExampleState();
}
class _TimerExampleState extends State<TimerExample> {
Timer _timer;
int _countdown;
@override
void initState() {
super.initState();
_countdown = 10;
startTimer();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_countdown.toString()),
RaisedButton(
onPressed: () => resetTimer(),
child: Text('Reset Timer'),
)
],
),
),
),
)
);
}
void startTimer() {
const oneSecond = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSecond,
(Timer timer) => setState(
() {
if (_countdown < 1) {
timer.cancel();
} else {
_countdown--;
}
},
),
);
}
void resetTimer() {
_timer.cancel();
_countdown = 10;
startTimer();
}
}
Upvotes: 1