The method 'compareTo' can't be unconditionally invoked because the receiver can be 'null'

Issue

How to fix this? Error Message: The method ‘compareTo’ 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 (‘!’).

enter image description here

Second Error: The argument type ‘Object?’ can’t be assigned to the parameter type ‘Object’.
How to fixed it?

enter image description here

Solution

It looks like you lack basic understanding about null safety features.
String? basically means that it’s a String that can be null. This can be done with any type. A question mark ? at the end of the type name makes it nullable, and if it isn’t there it can’t be null.

The language is designed in such a way that you can’t assign any objects that are nullable to variables that aren’t or use methods of objects that might be null.

There are several ways to handle this.

1) don’t make them nullable in the first place.

In your example, whatever the object is, it must have some field declared as String? name. Just remove the ? if possible. There’s a good chance it will make other errors pop up, but it should be solvable, at least in the case where you don’t allow it to be null. If for whatever reason you need it to be nullable this is not a solution.

2) tell the compiler that you are sure it’s not null in this situation

This is done by adding ! at the end of the variable. In your example that would be:
b.name!.compareTo(a.name!)
This is probably the easiest solution but the program will throw errors at runtime if they do happen to be null

3) provide a fallback value using ??

?? basically is an operator that returns the left side if it’s not null and otherwise the right side. You can use this to your advantage to provide fallback values. In your example you could do:
(b.name ?? '').compareTo(a.name ?? '')
This way it takes empty string in case the name is missing. This would be a safer option compared to option 2.

4) conditional calling using ?.

Maybe not applicable in your situation but good to know anyway. Let’s say some class A has the method getName and you have an object a of type A? and this code:

String? b = a.getName();

this is not allowed because a can be null. But you can write this:

String? b = a?.getName();

This basically mean that it executes getName() and assigns it to b when a is not null or just assigns null otherwise, which is possible because b is allowed to be null here. Therefore, this is NOT possible

String b = a?.getName();

Now b is defined as not being nullable and since the assignment possibly can provide null you are not allowed to.

Answered By – Ivo Beckers

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.