Skip to main content

Introduction

In Dart, you can read user input from the console using the stdin object from the dart:io library. This is essential for creating interactive command-line applications.

Reading String Input

To read text input from the user, use stdin.readLineSync():
import 'dart:io';

void main() {
  print("¿Cómo te llamas?");
  
  // El '?' es porque el valor puede ser nulo
  String? nombre = stdin.readLineSync();

  print("Hola, $nombre. ¡Mucho gusto!");
}
The return type is String? (nullable) because readLineSync() can return null if the input stream is closed or if an error occurs.

Reading Numeric Input

To read numeric values, you need to:
1

Read the input as a string

Use stdin.readLineSync() to get the user’s input
2

Parse the string to a number

Use int.parse() or double.parse() to convert the string to a number
3

Handle the nullable value

Use the ! operator to assert that the value is not null

Reading Integers

import 'dart:io';

void main() {
  print("Introduce tu edad:");
  
  // Leemos el texto y lo convertimos a entero
  int edad = int.parse(stdin.readLineSync()!);

  print("El año que viene tendrás ${edad + 1} años.");
}

Complete Example

Here’s a complete program that demonstrates reading both string and numeric input:
import 'dart:io';

void main() {
  print("¿Cómo te llamas?");
  
  // El '?' es porque el valor puede ser nulo
  String? nombre = stdin.readLineSync();

  print("Hola, $nombre. ¡Mucho gusto!");

  //Introducir valores numericos int o double
  print("Introduce tu edad:");
  
  // Leemos el texto y lo convertimos a entero
  int edad = int.parse(stdin.readLineSync()!);

  print("El año que viene tendrás ${edad + 1} años.");
}

Key Points

Import Required

Always import dart:io to access stdin

Nullable by Default

readLineSync() returns String? which must be handled

Parse Numbers

Use int.parse() or double.parse() for numeric input

Null Assertion

Use ! operator when you’re sure the input won’t be null

Best Practices

When using the ! operator, make sure the input won’t be null. Otherwise, your program will crash with a null reference error.
For more robust applications, consider using try-catch blocks when parsing numeric input to handle invalid input gracefully.
import 'dart:io';

void main() {
  print("Introduce tu edad:");
  
  try {
    int edad = int.parse(stdin.readLineSync()!);
    print("El año que viene tendrás ${edad + 1} años.");
  } catch (e) {
    print("Error: Por favor introduce un número válido");
  }
}

Build docs developers (and LLMs) love