【问题标题】:flutter : how to fix The method '[]' can't be unconditionally invoked because the receiver can be 'null'颤振:如何修复方法'[]'不能无条件调用,因为接收者可以是'null'
【发布时间】:2021-08-14 08:29:29
【问题描述】:

在迁移到 null safety 后,我正在尝试修复我的项目中的错误。我在这一行有错误:

 opacity: animation["opacity"],
        child: Transform.translate(
            offset: Offset(0, animation["translateY"]  ), child: child),

错误:不能无条件调用方法'[]',因为接收者可以是'null'

我的代码:

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: -130.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),
      ),
    );
  }
}

我该如何解决?

提前致谢

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    这意味着您的对象animation 可能是null(我猜它的类型是Map?)。 所以你不能直接做animation['yourKey'],因为null['yourKey']是无效的。

    您有几种解决方案:

    1. 如果可能,尝试将animation 的类型更改为Map
    2. 如果animation必须是Map?,但你确定在使用时它不会是null,你可以这样做
    animation!['yourKey']
    
    1. 如果可以是null,那么你可以这样做:
    animation?['yourKey'], // If it is okay to use a `null` value here
    animation?['yourKey'] ?? defaultValue, // If you need to use a non-null value
    

    例如,对于您的不透明度,您可以:

    opacity: animation?["opacity"] ?? 0,
    

    【讨论】:

      【解决方案2】:

      如果你使用 nullsafety

      final double? delay;
      final Widget? child;
      

      然后调用它们将在!

      例如延迟!还是孩子!

      【讨论】:

        猜你喜欢
        • 2022-08-24
        • 1970-01-01
        • 2023-04-10
        • 2021-08-27
        • 2023-03-05
        • 1970-01-01
        • 2022-08-21
        • 2021-10-05
        • 1970-01-01
        相关资源
        最近更新 更多