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

Flutter使用simpleanimation包遇[]运算符未定义错误求解决

问题解决方法

错误根源

  1. 参数顺序混淆:PlayAnimationBuilder的builder函数参数顺序是(context, value, child),你误将第三个参数(实际是Widget类型的child)命名为animation,导致调用animation?["opacity"]时,编译器认为你在对Widget使用[]运算符,而该类型并没有定义这个运算符。
  2. 错误的属性获取方式:Movie类并未实现[]索引运算符,它提供了类型安全的get<V>()方法来获取动画属性值。

修正后的代码

基础修正(使用字符串属性)

final tween = MovieTween();
tween.tween('opacity', Tween(begin: 0.0, end: 1.0),
    duration: const Duration(milliseconds: 500));

tween.tween('translateY', Tween(begin: 0.0, end: 1.0),
    duration: const Duration(milliseconds: 500),
    curve: Curves.easeOut);

return PlayAnimationBuilder<Movie>(
  delay: Duration(milliseconds: (500 * delay).round()),
  tween: tween,
  duration: tween.duration,
  // 修正参数顺序:第二个参数是Movie类型的动画快照,第三个是child
  builder: (context, movie, child) {
    return Opacity(
      // 使用Movie的get方法获取属性,指定类型为double
      opacity: movie.get<double>('opacity'),
      child: Transform.translate(
        offset: Offset(0, movie.get<double>('translateY')),
        child: child,
      ),
    );
  },
  // 传递child到builder的第三个参数
  child: child,
);

类型安全优化(推荐)

使用MovieTweenProperty定义类型安全的属性,避免字符串拼写错误:

// 定义全局或局部的类型安全属性
const opacityProperty = MovieTweenProperty<double>();
const translateYProperty = MovieTweenProperty<double>();

// 创建tween时使用定义好的属性
final tween = MovieTween();
tween.tween(opacityProperty, Tween(begin: 0.0, end: 1.0),
    duration: const Duration(milliseconds: 500));

tween.tween(translateYProperty, Tween(begin: 0.0, end: 1.0),
    duration: const Duration(milliseconds: 500),
    curve: Curves.easeOut);

return PlayAnimationBuilder<Movie>(
  delay: Duration(milliseconds: (500 * delay).round()),
  tween: tween,
  duration: tween.duration,
  builder: (context, movie, child) {
    return Opacity(
      // 使用from方法获取类型安全的属性值
      opacity: opacityProperty.from(movie),
      child: Transform.translate(
        offset: Offset(0, translateYProperty.from(movie)),
        child: child,
      ),
    );
  },
  child: child,
);

关键说明

  • PlayAnimationBuilder的builder函数中,第二个参数是泛型指定的Movie对象,它包含当前动画帧的所有属性快照。
  • 必须通过Movie类提供的get<V>()或MovieTweenProperty.from()方法获取属性值,不能直接使用[]运算符。
  • 确保将child参数传递给PlayAnimationBuilder,这样builder的第三个参数才能拿到正确的子组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:01:25