Non-null inference after null check with class fields

Skip to first unread message

Alec Henninger

Jan 5, 2021, 3:43:16 AM1/5/21
to Dart Misc
Hi dart-misc,

As I'm migrating to NNBD, I'm adding a! lot! of! exclamation! points!. Many (most?) of these should be inferable automatically IMO. Example:

void greet(String who) {
  print("Hello $who");

class Test {
  String? who = random.nextBool() ? "Bob" : null;

  void test() {
    if (who != null) {
      // Analyzer complains even though who is not null

The call to greet(who) inside the class method test gives an analyzer error.

You get similar errors trying to assign the nullable type to a non-null variable after the null check.

A similar scenario but with a variable declared inside a method does not give any errors:

void test() {
  String? who = random.nextBool() ? "Bob" : null;
  if (who != null) {
    // Analyzer knows this can't be null

I'm wondering if there is an issue open for this already (hard to find) or if this is intended behavior.



Jacob Bang

Jan 5, 2021, 3:59:12 AM1/5/21
Take a look at the answer I gave on stackoverflow to a similar question:
> --
> For more ways to connect visit
> ---
> You received this message because you are subscribed to the Google Groups "Dart Misc" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
> To view this discussion on the web visit

Jacob Bang / julemand101
Message has been deleted

Bob Nystrom

Jan 7, 2021, 5:20:35 PM1/7/21
to General Dart Discussion

On Tue, Jan 5, 2021 at 7:00 AM Alec Henninger <> wrote:
Hrm, unfortunate, but makes sense. I missed the "class fields" exception on the page.

I suppose it would be nice if either the analyzer could see that a class or field was not overridden, or there was a way to prevent overrides (which can be nice for other cases of course).

Yeah, this is a known pain point with null safety. It's the biggest issue we've noticed when migrating our own code to null safety, by a pretty big margin. We have some ideas on how to improve it, and some of those like you suggest involve being able to detect cases where a field can soundly be promoted and enable it there. There are a lot of tricky edge cases and subtleties which is one of the reasons we didn't get something like this working with the main null safety release, but I think there's room to improve things in the future.

In practice, I find this issue surprising and annoying, but not particularly difficult to manage once you're aware of and internalize the limitation.


– bob

Reply all
Reply to author
0 new messages