You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Animation<double>?无法赋值给Listenable类型报错如何解决?

报错原因

  • 第一个报错是因为AnimatedWidget的构造函数要求listenable参数为非空的Listenable类型,你的入参animation声明为可空类型Animation<double>?,类型不匹配。
  • 第二个报错是因为父类AnimatedWidget的listenable属性存储类型为Listenable,直接赋值给Animation<double>类型的变量需要显式类型转换。

解决方案

  1. 调整构造函数入参约束,将animation改为必传非空参数,避免空值传入
  2. 在build方法中对listenable做显式类型转换
  3. 若确实存在可能传入空值的场景,可补充非空断言+默认空动画兜底

修正后的完整代码如下:

class AnimatedProgressBar extends AnimatedWidget {
  // 移除参数可空标识,添加required强制非空传入
  AnimatedProgressBar({Key? key, required Animation<double> animation})
      : super(key: key, listenable: animation);

  Widget build(BuildContext context) {
    // 显式将listenable转换为Animation<double>类型
    final Animation<double> animation = listenable as Animation<double>;
    return Container(
      height: 6.0,
      width: animation.value,
      decoration: BoxDecoration(color: Colors.white),
    );
  }
}

如果业务场景需要支持可选传入animation,可以使用带默认兜底动画的版本:

class AnimatedProgressBar extends AnimatedWidget {
  AnimatedProgressBar({Key? key, Animation<double>? animation})
      // 空值时用静止的0值动画兜底
      : super(key: key, listenable: animation ?? AlwaysStoppedAnimation(0));

  Widget build(BuildContext context) {
    final Animation<double> animation = listenable as Animation<double>;
    return Container(
      height: 6.0,
      width: animation.value,
      decoration: BoxDecoration(color: Colors.white),
    );
  }
}

内容的提问来源于stack exchange,提问作者Kevnlan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 21:54:03