I have upgraded my Flutter project to newer Dart SDK version. I have an util that can return null object, it looks like this (example):

  static Item? getCurrentItem(List<Item> list, DateTime now) {
    return list.firstWhereOrNull((item) {
      return ItemUtils.hasItemStartedStarted(item, now) &&
          !ItemUtils.didItemFinish(item, now);

This static method returns null in one instance and later on when I try to do this:

final item = ItemUtils.getCurrentItem(items, now);
if (item != null && ItemUtils.someOtherMethod(item, now) {

The code runs inside StreamBuilder repeatedly, I have a Timer set up that re-renders it periodically.

It throws error Null check operator used on a null value. I checked value of item variable and it is null. But item != null reports false, why? I checked this inside debugger, is it possible it's some stale data because of StreamBuilder?

This code worked before. The migration tool used firstWhereOrNull method instead of .firstWhere(...., orElse: () => null) which I'm not sure where it comes from. Could that be the issue?

Solution 1: user3056783

So actually I completely misunderstood meaning behind !. and ?. syntax. From what I can tell !. is a cast syntax that tells Dart the object is not nullable.

For some reason I meant to use ?. for access on nullable object. Which explains the error message. I adjusted the code to use ?. instead of !. in my Flutter widget and the problem went away.

The most confusing part for me was the stack trace. The stack trace was pointing to line of code where I return StreamBuilder widget but did not point to usage of !. operator within its builder method. It would be nice if it actually pointed to the correct line.

Unfortunately I still don't understand why the variable item which was null did not evaluate to true with check item != null. I'm not sure if it's a problem with debugger but I also tried printing out the result of the expression and it was the same.