Dart null safety conditional statement?

Issue

So I have a class Cache which has a method compare that returns a bool.

I have an instance of this class that is nullable.

Cache? recent;

I want to executed a piece of code when recent is not null and compare returns false

Without null safety I would have just done

if(recent!=null && !recent.compare()){
  //code
}

How to do the same with null safety enabled?

When I try above with null safety I get

The method ‘compare’ 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 (‘!’)

When I try below

if(!recent?.compare()){
  //code
}

It gives me

A nullable expression can’t be used as a condition.
Try checking that the value isn’t ‘null’ before using it as a condition.

Solution

You can solve this problem either by

  • Using local variable (recommended)

    var r = recent; // Local variable
    if (r != null && !r.compare()) {
      // ...
    }
    
  • Using Bang operator (!)

    if (!recent!.compare()) { 
      // ...
    }
    

Answered By – CopsOnRoad

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *