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()!;
Share:
1,300
Ateeb Khan
Author by

Ateeb Khan

Updated on December 06, 2022

Comments

  • Ateeb Khan
    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
    quoci about 3 years
    you are welcome! Mark the question as resolved so others will know.
  • jamesdlin
    jamesdlin about 3 years
    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.