💙 Dart Basics: Taking User Input
User input is an important part of programming. It allows a program to receive information from the user and work with that information.
In Dart, we commonly use stdin.readLineSync() from the dart:io library to take input from the console.
📌 Basic Example
import 'dart:io';
void main() {
print("Enter your name:");
String? name = stdin.readLineSync();
print("Hello, $name!");
}
Here:
-
stdin.readLineSync()reads input from the user. -
String?means the input can be aStringornull. -
$nameis used to display the entered value.
📌 Taking Number Input
stdin.readLineSync() returns a string, so we need to convert it when we want a number.
import 'dart:io';
void main() {
print("Enter your age:");
int age = int.parse(stdin.readLineSync()!);
print("Your age is $age");
}
For decimal numbers, we can use double.parse():
double salary = double.parse(stdin.readLineSync()!);
💡 Key Takeaway
The basic flow is:
User Input → Read as String → Convert if Needed → Use the Value
Understanding user input helps build a strong foundation in Dart before moving into more advanced programming concepts.
Top comments (0)