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

Flutter Simple Animations空安全错误:无法无条件调用[]方法

修复simple_animations 5.x中MovieTween的空安全错误

你遇到的空安全错误是参数混淆导致的:在PlayAnimationBuilder的builder回调里,你把动画值对象(movie)和传入的子组件(child)搞混了。

错误原因

旧版本ControlledAnimation的builderWithChild参数顺序是(context, child, animation),而新版本PlayAnimationBuilder的builder参数顺序是(context, movie, child)——你错误地用child来获取动画值,但child是Widget类型,没有[]运算符,且可能为null,因此触发空安全警告。

修复后的代码

把获取动画值的child换成movie,再加上null断言!(因为我们明确通过MovieTween定义了这两个动画轨道,值必然存在):

import 'package:flutter/material.dart';
import 'package:simple_animations/simple_animations.dart';

class FadeAnimation extends StatelessWidget {
  final double delay;
  final Widget child;

  FadeAnimation(this.delay, this.child);

  @override
  Widget build(BuildContext context) {
    final tween = MovieTween();

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

    return PlayAnimationBuilder(
      delay: Duration(milliseconds: (500 * delay).round()),
      duration: tween.duration,
      tween: tween,
      child: child,
      builder: (context, movie, child) => Opacity(
        opacity: movie['opacity']!, // 替换为movie并添加null断言
        child: Transform.translate(
            offset: Offset(0, movie["translateY"]!), // 替换为movie并添加null断言
            child: child),
      ),
    );
  }
}

关键差异说明

旧版本(ControlledAnimation)新版本(PlayAnimationBuilder)
builderWithChild: (context, child, animation)builder: (context, movie, child)
用animation["key"]取动画值用movie["key"]取动画值

因为我们已经通过MovieTween定义了opacity和translateY两个轨道,所以可以安全地用!进行null断言,告诉Dart编译器这两个值不会为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:45:34