2
import 'dart:io';
main()
{
  print('What is your name: ');
  String name = stdin.readLineSync();
  print('Your age is = $name');
}

//I'm having this error when i'm taking user input in dart, Error: A value of type 'String?' can't be assigned to a variable of type 'String' because 'String?' is nullable and 'String' isn't.

Ateeb Khan
  • 253
  • 1
  • 2
  • 5

1 Answers1

2

I guess you are using null safety. The error occurs because stdin.readLineSync() returns a String? but you assing it on String name. To fix it add a ? or a !, but then make sure it is not null.

String? name = stdin.readLineSync();
String name = stdin.readLineSync()!;
quoci
  • 2,940
  • 1
  • 9
  • 21
  • you are welcome! Mark the question as resolved so others will know. – quoci Mar 20 '21 at 13:32
  • There's a big difference between `String? name = ...` and `String name = ...!`. Don't just blindly pick one. The latter will throw an exception if `readLineSync()` returns null, which can happen it immediately reaches EOF. – jamesdlin Mar 20 '21 at 14:09