Flutter中设置Tween的begin和end后AnimationController值仍从0.0到1.0是什么原因?
问题原因
你混淆了AnimationController和自定义Animation对象的功能边界:
AnimationController的value属性默认输出0.0到1.0之间的线性进度值,它的作用是管控动画的时长、播放状态、生成基础进度,不会受绑定的Tween参数影响。如果需要Controller本身输出自定义区间的数值,可以初始化时自定义lowerBound和upperBound参数,但这种方式仅支持数值类型,灵活性远低于Tween映射。- 你通过
Tween(begin: 50.0, end: 0.0).animate(controller1)生成的animation1对象,才是将Controller的0-1进度映射为你指定区间数值的载体,你需要读取的是animation1.value而非controller1.value。
修正示例
比如你要将动画值应用到组件的边距上,写法如下:
@override Widget build(BuildContext context) { return Container( // 这里取animation1的value,就是50.0到0.0变化的数值 margin: EdgeInsets.only(top: animation1.value), child: // 你的子组件 ); }
可选优化
你当前在动画监听里直接调用setState会让整个页面的build方法都重新执行,如果想要降低性能损耗,可以用AnimatedBuilder只刷新关联动画的组件部分:
// 初始化阶段可以去掉animation1的addListener回调,不需要手动调用setState @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animation1, builder: (context, child) { return Container( margin: EdgeInsets.only(top: animation1.value), child: child, ); }, child: // 你的子组件(这部分不会随动画重复重建) ); }
内容的提问来源于stack exchange,提问作者Defarine
相关产品推荐
相关产品推荐

