具有动态持续时间的Flutter AnimationController-错误:必须使用常量值初始化Const变量

时间:2019-11-25 18:03:28

标签: flutter dart flutter-animation

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

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);
}

1 个答案:

答案 0 :(得分:2)

您无法将这样的数据传递到const,因此解决方案是从const中删除Duration或仅使用一些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,
);