I am using TweenAnimationBuilder for creating countdown timer, like code below:
Without Controller
TweenAnimationBuilder<Duration>(
duration: Duration(seconds: 15),
tween: Tween(begin: Duration(seconds: 15), end: Duration.zero),
onEnd: () {
print('test repeat');
},
builder: (BuildContext context, Duration value, Widget child) {
final int seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$seconds',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 30)));
}),
With Controller
TweenAnimationBuilder<Duration>(
duration: Duration(seconds: 15),
tween: Tween(begin: Duration(seconds: 15), end: Duration.zero).animate(_animationController)
..addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) {
_animationController.reverse();
}
}),
onEnd: () {
print('test repeat');
},
builder: (BuildContext context, Duration value, Widget child) {
final int seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$seconds',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 30)));
}),
Before I added the controller, the animation work finely but only run for once (I need to repeat this TweenAnimationBuilder widget).
When I added the controller I Got Warning like
The argument type 'Animation<Duration>' can't be assigned to the parameter type 'Tween<Duration>'.
So how to make TweenAnimationBuilder with the animation and call the function repeatedly?
or is there any other solution than using TweenAnimationBuilder?
CodePudding user response:
You can't add animationController in TweenAnimationBuilder
I think you can use this if you need only countdown timer repeatedly
late Timer _timer;
int _start = 15;
void startTimer() {
const oneSec = Duration(seconds: 1);
_timer = Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
_start = 15;
} else {
setState(() {
_start--;
});
}
},
);
}
@override
void initState() {
startTimer();
super.initState();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Timer")),
body: Column(
children: <Widget>[Text("$_start")],
),
);
}
