具有动态持续时间的颤振动画控制器 - 错误:必须使用常量值初始化常量变量



我想从我的小部件参数设置动画持续时间,但它不起作用,因为持续时间想要用常量初始化

class CircularTimer extends StatefulWidget {
CircularTimer({@required this.seconds});
_CircularTimer createState() => _CircularTimer();
final seconds;
}
class _CircularTimer extends State<CircularTimer>
with SingleTickerProviderStateMixin {
Animation<double> animation;
AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(/*not working*/seconds: widget.seconds), vsync: this);
animation = Tween<double>(begin: 0, end: 300).animate(controller);
controller.forward();
}
@override
Widget build(BuildContext context) =>
CircularTimerWidget(animation: animation);
}

你不能将这样的数据传递给const,所以解决方案是从Duration中删除const,或者简单地使用一些const值。

解决方案:1

controller = AnimationController(
duration: Duration(seconds: widget.seconds), // remove const
vsync: this,
);

解决方案:2

controller = AnimationController(
duration: const Duration(seconds: 1), // some const value
vsync: this,
);

最新更新