4

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.

coder_86
  • 95
  • 2
  • 13

2 Answers2

5

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()) { 
      // ...
    }
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • 1
    Or: `if(!(recent?.compare() ?? true))` – julemand101 May 24 '21 at 09:57
  • 1
    @julemand101 Right! You can also do that. It's difficult to find out all the possible cases ;) But in that case, you need to provide a default value which may not be the best way in general. – CopsOnRoad May 24 '21 at 09:59
  • julemand101 I understand your approach, wasn't able to think about that :(. @CopsOnRoad I don't understand why the local variable approach works, and also what is Bang operator. Thanks for your answer, I will read about these. – coder_86 May 24 '21 at 13:18
  • 1
    @coder_86 Since you're using Dart null-safety, you should use one of the approaches I've mentioned or even julemand101's. For more detailed answer, you can take a look [here](https://stackoverflow.com/a/66941986/6618622) – CopsOnRoad May 24 '21 at 13:20
0

You can also declare the type as being dynamic recent; Which will match any 'data type' supplied at any given moment

Abdulfattah
  • 111
  • 2
  • 6