Console I/O

suggest change

Command-line applications rely on standard input (stdin), standard output (stdout), and standard error (stderr) to communicate with users and pipelines. In Dart, console input/output is provided by the dart:io library.


Writing Output: stdout vs stderr vs print()

Dart provides multiple ways to emit text to the terminal:

import 'dart:io';

void main() {
  // Standard output without newline
  stdout.write('Processing task... ');

  // Standard output with newline
  stdout.writeln('Done!');

  // Standard error
  stderr.writeln('Warning: Configuration file not found, using defaults.');
}

Reading Input from stdin

1. Synchronous Line Reading (readLineSync)

The simplest way to prompt for input is stdin.readLineSync():

import 'dart:io';

void main() {
  stdout.write('Please enter your name: ');
  final name = stdin.readLineSync();

  if (name == null || name.trim().isEmpty) {
    stderr.writeln('Error: No input provided.');
    exitCode = 1;
    return;
  }

  stdout.write('Enter your age: ');
  final ageInput = stdin.readLineSync();
  final age = int.tryParse(ageInput ?? '') ?? 0;

  print('Hello, $name! Next year you will be ${age + 1}.');
}

Note: stdin.readLineSync() returns null when standard input reaches EOF (End-Of-File). Always guard against null returns.

2. Reading Hidden Passwords (echoMode)

For password or sensitive credential entry, disable terminal echo so keystrokes are not visible on screen:

import 'dart:io';

String readPassword(String prompt) {
  stdout.write(prompt);
  
  // Disable echoing keystrokes to terminal
  stdin.echoMode = false;
  final password = stdin.readLineSync() ?? '';
  stdin.echoMode = true; // Restore echo mode
  
  stdout.writeln(); // Print trailing newline
  return password;
}

void main() {
  final secret = readPassword('Enter master password: ');
  print('Password length: ${secret.length} characters.');
}

Asynchronous Input Streaming

When reading piped data or long streams of lines without blocking the Dart event loop:

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

void main() async {
  print('Listening to piped input stream (press Ctrl+D or Ctrl+Z to finish):');

  final lineStream = stdin
      .transform(utf8.decoder)
      .transform(const LineSplitter());

  int count = 0;
  await for (final line in lineStream) {
    count++;
    print('Line $count: ${line.toUpperCase()}');
  }

  print('Total lines processed: $count');
}

Terminal Formatting and ANSI Colors

You can colorize output using ANSI escape codes. Before using ANSI codes, verify that the console is an interactive terminal (stdout.hasTerminal):

import 'dart:io';

class TerminalColor {
  static const reset = '\x1B[0m';
  static const red = '\x1B[31m';
  static const green = '\x1B[32m';
  static const yellow = '\x1B[33m';
  static const cyan = '\x1B[36m';
  static const bold = '\x1B[1m';
}

void main() {
  if (stdout.hasTerminal) {
    stdout.writeln('${TerminalColor.green}${TerminalColor.bold}[SUCCESS]${TerminalColor.reset} Build completed.');
    stderr.writeln('${TerminalColor.red}[ERROR]${TerminalColor.reset} Connection failed.');
    stdout.writeln('${TerminalColor.cyan}Info: Ready for requests.${TerminalColor.reset}');
  } else {
    // Non-interactive environment (e.g. redirected to a file or CI pipe)
    stdout.writeln('[SUCCESS] Build completed.');
  }
}

Process Exit Codes

Set the process exit code to notify invoking scripts or CI systems whether the command succeeded (0) or failed (non-zero):

import 'dart:io';

void main(List<String> args) {
  if (args.isEmpty) {
    stderr.writeln('Usage: app <command>');
    exitCode = 1; // Sets exit code gracefully on termination
    return;
  }

  // To terminate immediately without unwinding the stack:
  // exit(2);
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents