Flutter animations error, The method '[]' can't be unconditionally invoked because the receiver can be 'null'

Viewed 112

I am very new to flutter. I am having trouble with fixing this error.

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
    ),
  ),
);

and the error is The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!'). at the animation["opacity"] line. Can somebody please help

Complete code

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 = 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"],
        opacity: animation!(["opacity"]),

        child: Transform.translate(
         // offset: Offset(0, animation.["translateY"]), 
         offset: Offset(0, animation?["translateY"] ?? 0),
          child: child
        ),
      ),
    );
  }
}
1 Answers

Flutter supports what's called sound null safety. This helps you ensure values aren't null, and thereby prevents some runtime errors. You can read up on it here: https://dart.dev/null-safety/understanding-null-safety

In this case, I think it's caused by your object named animation, likely a map of some sort. In this case, the compiler is not sure whether or not the animation object is null or not. There's two things you can do: If you're certain animation is never gonna be null, you can tell that by adding a !:

Offset(0, animation!["translateY"]),

Or alternatively, if you think it might be null, you can tell that by adding a ?:

Offset(0, animation?["translateY"]),

But this will replace the translateY value with null if animation is null. In this case, it might be wise to define a default value to use when it resolves to null, using the ?? operator:

Offset(0, animation?["translateY"] ?? 0),

If you want to know more I advise you to read up on the dart.dev website or look up a helpful video or Medium post.

Related