5

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.

1

2 Answers 2

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()) { // ... } 
Sign up to request clarification or add additional context in comments.

4 Comments

Or: if(!(recent?.compare() ?? true))
@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.
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 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
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.