Flutter Dev
Flutter Dev

Reputation: 568

Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null

when i made flutter upgrade then run my app this error occurs.

../../../development/tools/flutter/.pub-cache/hosted/pub.dartlang.org/responsive_sizer-3.0.6+1/lib/src/helper.dart:56:33: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.

and also the app is getting me warning but still running normally Error here

Upvotes: 12

Views: 10026

Answers (2)

Martin Braun
Martin Braun

Reputation: 12629

If you need to fix this issue in a package and still want to support Flutter 2 it's actually better to bypass this issue like so:

/// This allows a value of type T or T? to be treated as a value of type T?.
///
/// We use this so that APIs that have become non-nullable can still be used
/// with `!` and `?` on the stable branch.
// See https://github.com/flutter/flutter/issues/64830
T? _ambiguate<T>(T? value) => value;

_ambiguate(SchedulerBinding.instance)!.addPostFrameCallback((_) {
    // ...
}

However, as soon as you ditch Flutter 2 support for further development, you should apply the accepted solution.

Ref: https://github.com/flutter/packages/pull/546/files

Upvotes: 1

hnnngwdlch
hnnngwdlch

Reputation: 3051

This is a warning not an error. In Flutter 3 the instance property on bindings such as WidgetsBinding and SchedulerBinding is now non-nullable, hence using the null-aware operator ? or the null assertion operation ! will lead to this warning.

If this warning originates from an external package as in your case, you could reach out to the developer and file an issue. Although for your specific package it should already be solved in version 3.0.7 or later as discussed here. So upgrading the package should solve the issue.

As far as your own code is concerned, you can run dart fix --apply and remove any null-aware or null assertion operators. E. g. change

SchedulerBinding.instance!.addPostFrameCallback(...);

to

SchedulerBinding.instance.addPostFrameCallback(...);

This page from the Flutter docs describes your options in greater detail.

Upvotes: 11

Related Questions