【问题标题】:error: The method '[]' can't be unconditionally invoked because the receiver can be 'null' [duplicate]错误:无法无条件调用方法“[]”,因为接收者可以为“null”[重复]
【发布时间】:2021-09-05 01:50:13
【问题描述】:

我知道解决方案很简单,但我是 nullsafety 和动画的新手,请帮我解决这个问题:

这里是代码:

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

  FadeAnimation(this.delay, this.child);

  @override
  Widget build(BuildContext context) {
    final tween = MultiTrackTween([
      Track("opacity")
          .add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)),
      Track("translateY").add(
          Duration(milliseconds: 500), Tween(begin: -30.0, end: 0.0),
          curve: Curves.easeOut)
    ]);

    return ControlledAnimation(
      delay: Duration(milliseconds: (500 * delay).round()),
      duration: tween.duration,
      tween: tween,
      child: child,
      builderWithChild: (context, child, animation) => Opacity(
        opacity: animation["opacity"],
        child: Transform.translate(
            offset: Offset(0, animation["translateY"]), child: child),
      ),
    );
  }
}

问题出在这 2 行

opacity: animation["opacity"],

还有这个:

 offset: Offset(0, animation["translateY"]), child: child),

注意:null 运算符不起作用。 感谢您的提前帮助。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    1. 好像Map,从您检索的值是nullable
    2. Opacity 小部件有必填字段opacity,不能是null
    3. Offset 也有必填字段,也不能是null

    所以你必须将这些值转换为非空值,例如:

      Opacity(
        opacity: animation?["opacity"] ?? .1, //we return default value (any suitable default value, for example 0.1) if animation["opacity"] returns null
        child: Transform.translate(
            offset: Offset(0, animation?["translateY"] ?? .1), child: child), //same
      )
    

    【讨论】:

    • 您好,谢谢或您的注意......但它不起作用......它说:错误:未为“对象”类型定义运算符“[]”。我该如何解决这个问题?
    • 我猜主要问题是这样的:信息:库包:simple_animations/simple_animations.dart' 是遗留的,不应导入到空安全库中。我必须更改版本或代码.......
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2021-08-27
    • 2021-10-05
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    相关资源
    最近更新 更多