N Kaushik

Solved - The argument type String? can't be assigned to the parameter type String

October 01, 2021

Introduction:

I faced this error while updating some old posts on Dart. This issue The argument type ‘String?’ can’t be assigned to the parameter type ‘String’ because ‘String?’ is nullable and ‘String’ isn’t you might face if you are trying to use old library or Flutter/Dart project.

Error:

Here is the full error:

Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't

Dart argument error

Reason and solution:

I was running a program similar to the below program:

import "dart:io";

void main() {
  var givenValue = stdin.readLineSync();
  var parsedValue = int.parse(givenValue);
}

readLineSync reads a line from stdin or console.

The problem is that readLineSync returns a String?.

If you are new to Dart null-safety, you can check the official guide here.

string? means it may be a string or null. But, we need to pass a non-null value to int.parse.

So, the error says that String? is nullable but String isn’t.

Now, if you want to fix this error, you need to check for null before trying to parse the value.

import "dart:io";

void main() {
  var givenValue = stdin.readLineSync();

  if(givenValue != null){
    var parsedValue = int.parse(givenValue);
  }
}

It will work.


Subscribe to my Newsletter