Flutter中Animation<double>?无法赋值给Listenable类型报错如何解决?
报错原因
- 第一个报错是因为
AnimatedWidget的构造函数要求listenable参数为非空的Listenable类型,你的入参animation声明为可空类型Animation<double>?,类型不匹配。 - 第二个报错是因为父类
AnimatedWidget的listenable属性存储类型为Listenable,直接赋值给Animation<double>类型的变量需要显式类型转换。
解决方案
- 调整构造函数入参约束,将
animation改为必传非空参数,避免空值传入 - 在
build方法中对listenable做显式类型转换 - 若确实存在可能传入空值的场景,可补充非空断言+默认空动画兜底
修正后的完整代码如下:
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
相关产品推荐
相关产品推荐

