How can i take user input in dart?
1,300
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()!;
Author by
Ateeb Khan
Updated on December 06, 2022Comments
-
Ateeb Khan over 1 year
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.
-
quoci about 3 yearsDid you enabled null safety?
-
jamesdlin about 3 years
-
-
quoci about 3 yearsyou are welcome! Mark the question as resolved so others will know.
-
jamesdlin about 3 yearsThere's a big difference between
String? name = ...
andString name = ...!
. Don't just blindly pick one. The latter will throw an exception ifreadLineSync()
returns null, which can happen it immediately reaches EOF.