๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart User Input

User input is text a person types while a program runs. Dart reads one typed line with stdin.readLineSync().

Reading a name

readLineSync reads the typed line into name. The greeting prints that name.

import 'dart:io';

void main() {
  var name = stdin.readLineSync();
  print('Hello, $name');
}

Reading an age as text

tryParse turns the typed text into the number 30. The print adds 1 and shows the age next year.

import 'dart:io';

void main() {
  var line = stdin.readLineSync();
  var age = int.tryParse(line ?? '') ?? 0;
  print('Next year: ${age + 1}');
}

No line arrives

No line arrives for this run, so readLineSync returns null. The ?? fallback prints No city given instead.

import 'dart:io';

void main() {
  var city = stdin.readLineSync();
  print(city ?? 'No city given');
}

Example

import 'dart:io';

void main() {
  var name = stdin.readLineSync() ?? 'friend';
  var line = stdin.readLineSync();
  var age = int.tryParse(line ?? '') ?? 0;
  print('Hello, $name');
  print('Age next year: ${age + 1}');
}

Key points

  • Use import 'dart:io'; at the top of the file to reach stdin.
  • stdin: the stream of lines a person types.
  • readLineSync(): a method that reads one line and returns a String?.
  • A returned line can be null when no line arrives.
  • Use int.tryParse to turn typed text into an int value or null.
  • Use ?? after a nullable value to supply a fallback value.

In this example, the first readLineSync reads Ana into name. The second readLineSync reads the text 30 into line. tryParse turns that text into the number 30. The prints show the greeting and then the age next year, 31.

Note

readLineSync returns the line without the newline at its end.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What type does stdin.readLineSync() return?