I got a trouble but can't solve. I have this code

void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
  }

And I got

The method 'addPostFrameCallback' 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 ('!').

Why and How can I fix that ?


Solution 1: Christopher Moore

WidgetsBinding.instance is not always initialized. runApp will do this for you so you only have to worry about it not being initialized if you're doing something outside of runApp, which you're not doing here.

In the relatively recent migration to null-safety they made WidgetsBinding.instance nullable as it's possible that it will not be initialized, evident from the ? at the end of it's type.

The solution is in your error message. Use either the bang operator ! or the conditional call operator ?.. The former will tell the compiler that you know that WidgetsBinding.instance will not be null when it's used and throw an exception if you're wrong. The latter will do nothing if it's null.

I would recommend using the former, the ! operator, as it's expected that WidgetsBinding.instance will never be null when you use it here and it may help find bugs down the line.


Examples:

Bang operator !:

void initState() {
  super.initState();
  WidgetsBinding.instance!.addPostFrameCallback((_) => yourFunction(context));
}

Conditional call ?.:

void initState() {
  super.initState();
  WidgetsBinding.instance?.addPostFrameCallback((_) => yourFunction(context));
}