Getting user input is essential for interactive applications. In Dart, you can read input from the console using the dart:io
library. This allows your program to respond dynamically based on user input. Below is a detailed explanation of how to get user input, including example code, syntax, and the concept of type conversion.
Understanding User Input
Input
Input refers to the data provided by the user, which can be in various forms, such as strings, numbers, or other data types.
Output
Output is the data displayed to the user after processing the input. It can be a result, confirmation, or any other information.
Note: When working with user input, it's important to handle different data types and validate inputs to prevent errors.
Types of Input
1. Reading String Input
You can read a line of input from the user as a string using the stdin.readLineSync()
method.
Syntax:
String? variableName = stdin.readLineSync();
Example Program:
import 'dart:io';
void main() {
stdout.write('Enter your name: ');
String? name = stdin.readLineSync(); // Read user input
print('Hello, $name!'); // Output the greeting }
Explanation:
import 'dart:io';
: Imports thedart:io
library, which provides input and output functionalities.stdout.write('Enter your name: ');
: Displays a prompt for the user to enter their name without a newline.String? name = stdin.readLineSync();
: Reads a line of input from the user and stores it in the variablename
. The input is of typeString?
, meaning it can benull
.print('Hello, $name!');
: Outputs a greeting that includes the user's name.
2. Reading Numeric Input
To read numeric input, you will first read it as a string and then convert it to the desired numeric type (e.g., int
or double
).
Syntax:
int variableName = int.parse(stringInput);
double variableName = double.parse(stringInput);
Example Program:
import 'dart:io';
void main() {
stdout.write('Enter your age: ');
String? input = stdin.readLineSync(); // Read user input
// Convert string input to integer int age = int.parse(input!);
print('You are $age years old.'); // Output the age }
Explanation:
String? input = stdin.readLineSync();
: Reads user input as a string.int age = int.parse(input!);
: Converts the string input to an integer usingint.parse()
. The!
operator asserts thatinput
is notnull
.print('You are $age years old.');
: Outputs the user's age.
Understanding Type Conversion
Type conversion is the process of converting a value from one data type to another. In Dart, this is particularly important when you receive input from users, as input is usually read as a string. To perform mathematical operations or use the input in a different context, you must convert it to the appropriate type.
Common Conversion Methods
- String to Integer:
- Use
int.parse(String input)
to convert a string representation of an integer into anint
. Example:
String ageInput = '25'; int age = int.parse(ageInput); // Converts string to int
- Use
- String to Double:
- Use
double.parse(String input)
to convert a string representation of a decimal number into adouble
. Example:
String heightInput = '1.75'; double height = double.parse(heightInput); // Converts string to double
- Use
- Error Handling:
- It's crucial to handle potential errors during conversion, especially when the input may not be in the expected format. Dart will throw a
FormatException
if the conversion fails. Example:
try { double weight = double.parse(input!); } catch (e) { print('Invalid input. Please enter a valid number.'); }
- It's crucial to handle potential errors during conversion, especially when the input may not be in the expected format. Dart will throw a
Example Program with Type Conversion
Here's a complete program that combines user input and type conversion:
Example Program:
import 'dart:io';
void main() {
stdout.write('Enter your height in meters (e.g., 1.75): ');
String? input = stdin.readLineSync(); // Read user input
try {
// Convert string input to double double height = double.parse(input!);
// Calculate height in centimeters double heightInCm = height * 100;
print('Your height in centimeters is ${heightInCm.toStringAsFixed(2)} cm.'); // Output the height } catch (e) {
print('Invalid input. Please enter a valid number.'); // Error message }
}
Explanation:
stdout.write('Enter your height in meters (e.g., 1.75): ');
: Prompts the user to enter their height in meters.String? input = stdin.readLineSync();
: Reads the height input as a string.try { ... } catch (e) { ... }
: A try-catch block is used to handle potential errors during type conversion.double height = double.parse(input!);
: Converts the string input to a double.double heightInCm = height * 100;
: Calculates the height in centimeters by multiplying the height in meters by 100.print('Your height in centimeters is ${heightInCm.toStringAsFixed(2)} cm.');
: Outputs the height in centimeters, formatted to two decimal places.- If the input is invalid, it catches the error and displays an error message.
Conclusion
Getting user input in Dart is straightforward and allows for dynamic interaction in your applications. Understanding how to read different types of input and handle type conversion is crucial for building robust programs. By practicing with the examples provided, you can enhance your skills in handling user inputs effectively, ensuring a better user experience in your applications. Type conversion ensures that the data received from users is in the correct format for further processing, allowing your application to function correctly and efficiently.
PLAY QUIZ