How do I read console input / stdin in Dart?

import 'dart:io';

void main(){
  stdout.write("Enter your name : ");
  var name = stdin.readLineSync();
  stdout.write(name);
}

Output

Enter your name : Jay
Jay

By default readLineSync() takes input as string. But If you want integer input then you have to use parse() or tryparse().


The following should be the most up to date dart code to read input from stdin.

import 'dart:async';
import 'dart:io';
import 'dart:convert';

void main() {
  readLine().listen(processLine);
}

Stream<String> readLine() => stdin
    .transform(utf8.decoder)
    .transform(const LineSplitter());

void processLine(String line) {
  print(line);
}

The readLineSync() method of stdin allows to capture a String from the console:

import 'dart:convert';
import 'dart:io';

void main() {
  print('1 + 1 = ...');
  var line = stdin.readLineSync(encoding: utf8);
  print(line?.trim() == '2' ? 'Yup!' : 'Nope :(');
}

Old version:

import 'dart:io';

main() {
    print('1 + 1 = ...');
    var line = stdin.readLineSync(encoding: Encoding.getByName('utf-8'));
    print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
}

With M3 dart classes like StringInputStream are replaced with Stream, try this:

import 'dart:io';
import 'dart:async';

void main() {
  print("Please, enter a line \n");
  Stream cmdLine = stdin
      .transform(new StringDecoder())
      .transform(new LineTransformer());

  StreamSubscription cmdSubscription = cmdLine.listen(
    (line) => print('Entered line: $line '),
    onDone: () => print(' finished'),
    onError: (e) => /* Error on input. */);


}

Tags:

Dart

Dart Io