Reading User Input
Prerequisites: Type conversion
In a command-line program, stdin.readLineSync() from dart:io waits
for the user to type a line and press Enter. It returns a String? —
null if there's no more input.
Example
import 'dart:io';
void main() {
stdout.write("What's your name? ");
final name = stdin.readLineSync() ?? '';
print('Nice to meet you, $name!');
}
Expected output
What's your name? Ada
Nice to meet you, Ada!
(Ada is what the user typed.) stdout.write keeps the cursor on the
same line as the question.
Reading numbers
import 'dart:io';
void main() {
stdout.write('How old are you? ');
final age = int.tryParse(stdin.readLineSync()?.trim() ?? '');
if (age == null) {
print('Please enter a whole number.');
return;
}
print("In ten years you'll be ${age + 10}.");
}
Note: DartPad, Flutter apps, and web apps don't read keyboard input
this way. Run these examples with dart run in a terminal.
Practice
Ask the user for their favorite color and print it back in capitals:
BLUE is a great color!.
Show solution
import 'dart:io';
void main() {
stdout.write('Favorite color? ');
final color = stdin.readLineSync() ?? '';
print('${color.toUpperCase()} is a great color!');
}