How do I read console input / stdin in Dart?

Issue

How do I read console input from stdin in Dart?

Is there a scanf in Dart?

Solution

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 :(');
}

Answered By – Renaud Denis

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *