【问题标题】:Flutter AnimationController with dynamic duration - error: Const variables must be initialized with a constant value具有动态持续时间的 Flutter AnimationController - 错误:必须使用常量值初始化常量变量
【发布时间】:2019-11-25 18:03:28
【问题描述】:

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

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

【问题讨论】:

    标签: flutter dart flutter-animation


    【解决方案1】:

    您不能将这样的数据传递给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,
    );
    

    【讨论】:

    • 谢谢,我使用了解决方案 1 - const 最初在我使用的示例代码中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多