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.
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.
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.");}
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.");}
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"); }}