Console I/O
suggest changeCommand-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:
print(message): Automatically appends a newline character (\n) and directs output tostdout.stdout.write(message): Emits text without appending a trailing newline (useful for command prompts).stdout.writeln(message): Emits text followed by a platform-specific newline.stderr.writeln(message): Emits error messages to the standard error stream, allowing users to separate normal program output from diagnostic errors.
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()returnsnullwhen standard input reaches EOF (End-Of-File). Always guard againstnullreturns.
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
- Differentiate
stdoutandstderr: Emit structured data and success messages tostdout, and errors or diagnostics tostderrso users can cleanly pipe output. - Always restore
echoModein atry-finallyblock: If an exception occurs while reading a password, ensurestdin.echoMode = trueis restored. - Check
stdout.hasTerminal: Do not print raw ANSI escape codes if output is being redirected to a log file or piped to another tool.