Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Resolve The Argument type 'String?' can't be assign to parameter type 'String'

In dart sdk greater than 2.12.0 we are often using '?' to make sure that argument can have null values also, but how to convert datatype with ? to datatype without ? or vice versa. what can be the most preferred way to sort out 'int?' can't of type 'int'.

like image 789
Rishabh Bhardwaj Avatar asked May 11 '21 23:05

Rishabh Bhardwaj


3 Answers

You get this error on assigning a nullable string (String?) to a non-nullable string (String). For ex:

String? s = 'a';

int expectsString(String s) => s.length;

void main() {
  expectsString(s); // <-- Error
}

The solution is to either provide a non-nullable String. You can do that using:

(1) Local variable:

void main() {
  var s1 = s; // Local variable 
  expectsString(s1 ?? 'default value');
}

(2) Bang operator:

void main() {
  expectsString(s!); // Bang operator
}
like image 77
CopsOnRoad Avatar answered Oct 12 '22 14:10

CopsOnRoad


The null safety is a method to say that a type can or can not be null, you are not wrapping anything inside an object, so you don't have anything to unwrap.

Maybe you are confusing this with the optional type from functional language or Java. Where an optional type can be unwrapped if it contains a value.

With dart, google take another decision, to give the possibility to the user to write a clean code without check if an object is null and vice versa, so with null safety you have the mathematical proof that your code doesn't access to null reference.

So, if you need to unwrap the null object or you don't need it, or you need a check like that

foo(int? i) {
  if (i != null) {
    print(i + 1);
  }
}

I want to point out a great reference of one dart developer that describe why to google take this decision https://medium.com/dartlang/why-nullable-types-7dd93c28c87a

like image 31
vincenzopalazzo Avatar answered Oct 12 '22 13:10

vincenzopalazzo


I had a similar issue in one of my flutter apps, and I had fixed it with type casting from String? to String.

just like in the code below:

// I'm using a List with one element to generate the same error,
// because the error doesn't happen for one single variable.

List<String?> imageUrls = ['https://www.example.com/example_image.png',];

// you cast the element imageUrls[0] with 'as' keyword from String? to String

NetworkImage(imageUrls[0] as String); // NetworkImage() takes String parameter
like image 43
OMBHD Avatar answered Oct 12 '22 14:10

OMBHD