Input and Output in Dart
In programming, input is data that your program receives from the user or external sources, while output is data that your program displays or sends back. Think of it like a conversation - you ask questions (output) and receive answers (input)!
Getting Input from User
Dart provides the stdin.readLineSync() method to read input from the user. You'll need to import the dart:io library to use this functionality.
import 'dart:io';
void main() {
print('What is your name?');
String? name = stdin.readLineSync();
print('Hello, $name!');
}
Important Notes about Input
stdin.readLineSync()returns aString?(nullable string)- It reads the entire line until the user presses Enter
- Always handle the possibility of null input
Displaying Output
Dart offers several ways to display output:
Using print()
The most common way to display output:
void main() {
print('Hello, World!');
print('Welcome to Dart programming!');
}
Using stdout.write()
For output without automatic line breaks:
import 'dart:io';
void main() {
stdout.write('Enter your age: ');
String? age = stdin.readLineSync();
print('You are $age years old');
}
Working with Different Data Types
Since stdin.readLineSync() always returns a string, you'll often need to convert it to other data types:
import 'dart:io';
void main() {
// Reading a number
print('Enter your age:');
String? input = stdin.readLineSync();
int age = int.parse(input ?? '0');
// Reading a decimal number
print('Enter your height in meters:');
String? heightInput = stdin.readLineSync();
double height = double.parse(heightInput ?? '0.0');
print('Age: $age, Height: ${height}m');
}
String Interpolation in Output
Make your output more dynamic using string interpolation:
import 'dart:io';
void main() {
print('Enter your first name:');
String? firstName = stdin.readLineSync();
print('Enter your last name:');
String? lastName = stdin.readLineSync();
// Using string interpolation
print('Full name: $firstName $lastName');
print('Initials: ${firstName?[0]}${lastName?[0]}');
}
Common Input/Output Patterns
| Method | Purpose | Example |
|---|---|---|
print() | Display text with newline | print('Hello'); |
stdout.write() | Display text without newline | stdout.write('Name: '); |
stdin.readLineSync() | Read user input | String? input = stdin.readLineSync(); |
int.parse() | Convert string to integer | int num = int.parse('42'); |
double.parse() | Convert string to double | double price = double.parse('19.99'); |