In Dart, handling user input and displaying output is straightforward, especially for command-line or console-based applications. Here’s a guide on taking user input and producing output in Dart.
To display output in Dart, you use the print function. This function sends text to the console, making it useful for showing results, debugging, or providing feedback to users.
Example:
void main() {
print("Hello, World!");
int result = 5 + 3;
print("The result is: $result");
}
In this example:
print("Hello, World!") displays the string in the console.
The second print statement includes a variable within a string using Dart's string interpolation ($variableName).
Dart provides a way to capture user input using the dart:io library, which is specifically for console-based input and output in Dart.
To use dart:io, you need to import it:
import 'dart:io';
Syntax for Capturing User Input:
stdin.readLineSync(): Reads a line of input from the user as a string.
int.parse(): Converts a string input to an integer.
double.parse(): Converts a string input to a double.
Example of Taking User Input (String):
import 'dart:io';
void main() {
print("Enter your name:");
String? name = stdin.readLineSync(); // Reads input as a string
print("Hello, $name!");
}
In this example:
stdin.readLineSync() reads a line of input from the user.
The String? syntax means name can hold null, which is useful if no input is entered.
Example of Taking User Input (Integer):
import 'dart:io';
void main() {
print("Enter your age:");
int age = int.parse(stdin.readLineSync()!); // Converts input to integer
print("You are $age years old.");
}
In this example:
stdin.readLineSync() gets input as a string.
int.parse() converts the string to an integer.
The ! operator after readLineSync() tells Dart the input is non-null, avoiding a compile-time error.
Let's say we want to create a simple program that asks the user for their name and age, then calculates the age in 5 years.
import 'dart:io';
void main() {
// Take name as input
print("Enter your name:");
String? name = stdin.readLineSync();
// Take age as input and convert to integer
print("Enter your age:");
int age = int.parse(stdin.readLineSync()!);
// Calculate future age
int futureAge = age + 5;
print("Hello, $name! In 5 years, you will be $futureAge years old.");
}
In this example:
The program first asks for the user’s name.
Then it asks for the user’s age, converting the input to an integer.
Finally, it calculates the age in 5 years and displays the result.
If you need to accept decimal numbers, use double.parse() instead of int.parse().
Example:
import 'dart:io';
void main() {
print("Enter a decimal number:");
double number = double.parse(stdin.readLineSync()!);
print("You entered: $number");
}
If a user enters an invalid value (e.g., entering a non-integer where an integer is expected), int.parse() and double.parse() will throw an error. To handle this, you can use a try-catch block.
Example with Error Handling:
import 'dart:io';
void main() {
try {
print("Enter your age:");
int age = int.parse(stdin.readLineSync()!);
print("You are $age years old.");
} catch (e) {
print("Invalid input. Please enter a valid integer.");
}
}
In Dart, the print function provides a straightforward way to display output, while the dart:io library’s stdin.readLineSync() captures user input from the console. For number conversion, int.parse() and double.parse() are commonly used, and error handling with try-catch can help manage invalid inputs gracefully. This is especially useful in console-based applications and helps in building interactive applications in Dart.
-----------------------------------------------------------------------------------------------------
In Dart, user input and output are essential for interactive programs. Dart provides several ways to handle input and output, primarily through the dart:io library for console input/output, and the print() function for simple output.
The most common method for outputting information in Dart is the print() function. This function sends a string or other object to the console.
void main() {
print("Hello, Dart!"); // Output: Hello, Dart!
}
You can print variables as well:
void main() {
var name = "Alice";
print("Hello, $name!"); // Output: Hello, Alice!
}
For formatted output, you can use string interpolation or the String.format method (Dart 3 onwards).
void main() {
var age = 25;
print("I am $age years old."); // Output: I am 25 years old.
}
To get user input, you need to use the dart:io library, which provides the stdin object to read data from the console.
First, ensure you import the dart:io library:
import 'dart:io';
Basic User Input:
The stdin.readLineSync() method reads a line of text from the user.
import 'dart:io';
void main() {
// Request input from the user
print("Enter your name:");
String? name = stdin.readLineSync(); // Takes input as a string
// Output the input
print("Hello, $name!");
}
User Input for Numbers:
When taking numeric input, the returned value is a String, so you must convert it to a number using int.parse() or double.parse().
import 'dart:io';
void main() {
print("Enter your age:");
String? input = stdin.readLineSync();
// Convert the string input to an integer
int age = int.parse(input!); // Ensure the input is non-null
print("Your age is $age years.");
}
To avoid errors from invalid or null inputs, you can use error handling like try-catch blocks:
import 'dart:io';
void main() {
print("Enter a number:");
String? input = stdin.readLineSync();
try {
int number = int.parse(input!);
print("You entered the number: $number");
} catch (e) {
print("Invalid input. Please enter a valid number.");
}
}
This handles cases where the user enters non-numeric values.
You can combine loops to repeatedly ask the user for input until valid data is provided:
import 'dart:io';
void main() {
int? age;
// Repeat until valid input is given
while (age == null) {
print("Please enter your age:");
String? input = stdin.readLineSync();
try {
age = int.parse(input!);
print("Your age is $age years.");
} catch (e) {
print("Invalid input. Please enter a valid number.");
}
}
}
For more advanced input/output like reading from and writing to files, you can use the dart:io library's file system functions. For example:
Writing to a File
import 'dart:io';
void main() async {
var file = File('output.txt');
// Writing text to the file
await file.writeAsString('Hello, Dart!');
print("Text has been written to output.txt.");
}
Reading from a File
import 'dart:io';
void main() async {
var file = File('output.txt');
// Reading content from the file
String content = await file.readAsString();
print("File content: $content");
}
If you need to get multiple inputs from a user, you can validate and collect inputs as shown here:
import 'dart:io';
void main() {
print("Enter your first name:");
String? firstName = stdin.readLineSync();
print("Enter your last name:");
String? lastName = stdin.readLineSync();
print("Hello, $firstName $lastName!");
}
In addition to interactive input, Dart allows you to pass arguments to a program when running it via the command line using the args parameter in the main() function.
Example to run: dart program.dart argument1 argument2
void main(List<String> arguments) {
if (arguments.isEmpty) {
print("No arguments passed.");
} else {
print("Arguments passed: ${arguments.join(", ")}");
}
}
print(): Displays output to the console.
stdin.readLineSync(): Reads a line of input from the user (returns String?).
int.parse() / double.parse(): Converts a string to a numeric value.
try-catch: Handles errors when parsing input.
File(): Used for reading and writing files (advanced I/O).
import 'dart:io';
void main() {
// Request input from the user
print("Enter your name:");
String? name = stdin.readLineSync(); // Takes input as a string
// Output the input
print("Hello, $name!");
}
import 'dart:io';
void main() {
print("Enter your age:");
String? input = stdin.readLineSync();
// Convert the string input to an integer
int age = int.parse(input!); // Ensure the input is non-null
print("Your age is $age years.");
}
import 'dart:io';
void main() {
print("Enter the first number:");
int num1 = int.parse(stdin.readLineSync()!);
print("Enter the second number:");
int num2 = int.parse(stdin.readLineSync()!);
int sum = num1 + num2;
print("The sum is: $sum");
}
import 'dart:io';
void main() {
print("Enter first number:");
int num1 = int.parse(stdin.readLineSync()!);
print("Enter second number:");
int num2 = int.parse(stdin.readLineSync()!);
int product = num1 * num2;
print("The product is: $product");
}
import 'dart:io';
void main() {
print("Enter the first number:");
int num1 = int.parse(stdin.readLineSync()!);
print("Enter the second number:");
int num2 = int.parse(stdin.readLineSync()!);
int difference = num1 - num2;
print("The difference is: $difference");
}
import 'dart:io';
void main() {
print("Enter the numerator:");
double num1 = double.parse(stdin.readLineSync()!);
print("Enter the denominator:");
double num2 = double.parse(stdin.readLineSync()!);
if (num2 == 0) {
print("Cannot divide by zero.");
} else {
double result = num1 / num2;
print("The result is: $result");
}
}
import 'dart:io';
void main() {
print("Enter a number to find its square:");
int num = int.parse(stdin.readLineSync()!);
int square = num * num;
print("The square of $num is: $square");
}
import 'dart:io';
void main() {
print("Enter a number:");
int num = int.parse(stdin.readLineSync()!);
if (num % 2 == 0) {
print("$num is even.");
} else {
print("$num is odd.");
}
}
import 'dart:io';
void main() {
print("Enter a number:");
int num = int.parse(stdin.readLineSync()!);
if (num > 0) {
print("$num is positive.");
} else if (num < 0) {
print("$num is negative.");
} else {
print("$num is zero.");
}
}
import 'dart:io';
void main() {
print("Enter a year:");
int year = int.parse(stdin.readLineSync()!);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
print("$year is a leap year.");
} else {
print("$year is not a leap year.");
}
}
import 'dart:io';
void main() {
print("Enter your name:");
String? name = stdin.readLineSync();
print("Enter your age:");
int age = int.parse(stdin.readLineSync()!);
print("Hello $name, you are $age years old.");
}
import 'dart:io';
void main() {
print("Enter three names, separated by commas:");
String? input = stdin.readLineSync();
List<String> names = input!.split(',');
for (var name in names) {
print("Hello, $name!");
}
}
import 'dart:io';
void main() {
print("Enter the base of the triangle:");
double base = double.parse(stdin.readLineSync()!);
print("Enter the height of the triangle:");
double height = double.parse(stdin.readLineSync()!);
double area = 0.5 * base * height;
print("The area of the triangle is: $area");
}
import 'dart:io';
void main() {
print("Enter temperature in Fahrenheit:");
double fahrenheit = double.parse(stdin.readLineSync()!);
double celsius = (fahrenheit - 32) * 5 / 9;
print("$fahrenheit Fahrenheit is $celsius Celsius.");
}
import 'dart:io';
void main() {
print("Enter temperature in Celsius:");
double celsius = double.parse(stdin.readLineSync()!);
double fahrenheit = (celsius * 9 / 5) + 32;
print("$celsius Celsius is $fahrenheit Fahrenheit.");
}
import 'dart:io';
void main() {
print("Enter a number to find its factorial:");
int num = int.parse(stdin.readLineSync()!);
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
print("The factorial of $num is $factorial");
}
import 'dart:io';
void main() {
print("Enter the principal amount:");
double principal = double.parse(stdin.readLineSync()!);
print("Enter the rate of interest:");
double rate = double.parse(stdin.readLineSync()!);
print("Enter the time in years:");
double time = double.parse(stdin.readLineSync()!);
double interest = (principal * rate * time) / 100;
print("The simple interest is: $interest");
}
import 'dart:io';
void main() {
print("Enter a number N to find the sum of first N natural numbers:");
int num = int.parse(stdin.readLineSync()!);
int sum = (num * (num + 1)) ~/ 2;
print("The sum of first $num natural numbers is $sum.");
}
import 'dart:io';
void main() {
print("Enter a string:");
String? input = stdin.readLineSync();
String reversed = input!.split('').reversed.join('');
print("The reverse of the string is: $reversed");
}
import 'dart:io';
void main() {
print("Enter a number to check if it's prime:");
int num = int.parse(stdin.readLineSync()!);
bool isPrime = true;
for (int i = 2; i <= num ~/ 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && num > 1) {
print("$num is a prime number.");
} else {
print("$num is not a prime number.");
}
}
Basic arithmetic operations (addition, subtraction, multiplication, division).
Condition checks (even/odd, positive/negative, leap year).
String manipulation (reversing strings, formatting output).
More complex calculations (factorial, interest, sum of natural numbers).
Conversions (Fahrenheit to Celsius, Celsius to Fahrenheit).
Prime number checks and triangle area calculations.
import 'dart:io';
void main() {
// Output
print('Enter your name:');
// Input
String? name = stdin.readLineSync();
// Output
print('Hello, $name!');
}
Ex=
import 'dart:io';
void main()
{
print("Enter name");
String nem = stdin.readLineSync()!;
print("Name is $nem");
print('Enter age');
int nm = int.parse(stdin.readLineSync()!);
print("Age is $nm");
}
ex=
import 'dart:io';
void main(){
int no;
String st;
double db;
print ('Enter name');
st=stdin.readLineSync()!;
print('Name is $st');
print ('Enter a number');
no=int.parse(stdin.readLineSync()!);
print('number is $no');
print ('enter string/ Double value');
db=double.parse(stdin.readLineSync()!);
print ('Double value is $db');
}
import 'dart:io';
void main() {
print('Enter your age:');
String? input = stdin.readLineSync();
int? age = int.tryParse(input!);
if (age != null) {
print('You are $age years old.');
} else {
print('Invalid input. Please enter a number.');
}
}
import 'dart:io';
void main() {
while (true) {
print('Enter a number (or type "exit" to quit):');
String? input = stdin.readLineSync();
if (input == 'exit') {
print('Goodbye!');
break;
}
int? number = int.tryParse(input!);
if (number != null) {
print('You entered: $number');
} else {
print('Please enter a valid number.');
}
}
}
Ex=
import 'dart:io';
void main()
{
var list = <int>[];
for(int i = 0; i<=5 ;i++)
{
print("Enter $i data");
int nm = int.parse(stdin.readLineSync()!);
list.add(nm);
}
for(var itm in list)
{
print(itm);
}
}
import 'dart:io';
void main() {
print('Enter your name:');
String? name = stdin.readLineSync();
print('Enter your age:');
String? ageInput = stdin.readLineSync();
int age = int.tryParse(ageInput!) ?? 0;
print('Hello, $name! You are $age years old.');
}
import 'dart:io';
void main() {
String name = getName(); //function
int age = getAge(); //function
print('Hello, $name! You are $age years old.');
}
String getName() {
print('Enter your name:');
return stdin.readLineSync()!;
}
int getAge() {
print('Enter your age:');
String? ageInput = stdin.readLineSync();
return int.tryParse(ageInput!) ?? 0;
}
import 'dart:io';
void main() {
String nm;
int ag;
double per;
List<int> lst;
Set<String> str;
print('Enter your name-');
nm = stdin.readLineSync()!;
print('Name is -$nm');
print('Enter your age-');
ag = int.parse(stdin.readLineSync()!);
print('Age is- $ag');
print('Enter your 10th percentage-');
per = double.parse(stdin.readLineSync()!);
print('10th percentage is-$per');
}
Dart program that generates a Fibonacci series based on user input
import 'dart:io';
void main() {
print("Enter the number of terms for the Fibonacci series: ");
String input = stdin.readLineSync()!;
int n = int.parse(input);
if (n <= 0) {
print("Please enter a positive integer.");
} else {
print("Fibonacci Series with $n terms:");
for (int i = 0; i < n; i++) {
print(fibonacci(i));
}
}
}
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
WADP which accepts the radius of a circle from the user and find the area of circle.
Code -
import 'dart:io';
main() {
const pi = 3.14;
dynamic radius = stdin.readLineSync();
radius = double.parse(radius);
print('The area is: ${pi*radius*radius}');
}
---------------------------------------------------------------------------------------------------------------
Make sure to import dart:io to allow reading input in Dart.
import 'dart:io';
import 'dart:io';
void main() {
print("Enter the first number:");
int num1 = int.parse(stdin.readLineSync()!);
print("Enter the second number:");
int num2 = int.parse(stdin.readLineSync()!);
int sum = num1 + num2;
print("Sum of the two numbers is: $sum");
}
import 'dart:io';
void main() {
print("Enter a sentence:");
String? sentence = stdin.readLineSync();
int wordCount = sentence!.split(" ").length;
print("The number of words in the sentence is: $wordCount");
}
import 'dart:io';
void main() {
print("Enter your age:");
int age = int.parse(stdin.readLineSync()!);
if (age >= 18) {
print("You are eligible to vote.");
} else {
print("You are not eligible to vote.");
}
}
import 'dart:io';
void main() {
print("Enter numbers separated by spaces:");
String? input = stdin.readLineSync();
List<String> numbers = input!.split(" ");
int sum = 0;
for (String number in numbers) {
sum += int.parse(number);
}
print("The sum of the numbers is: $sum");
}
import 'dart:io';
void main() {
print("Enter the radius of the circle:");
double radius = double.parse(stdin.readLineSync()!);
double area = 3.14159 * radius * radius;
print("The area of the circle is: $area");
}
import 'dart:io';
void main() {
print("Enter a year:");
int year = int.parse(stdin.readLineSync()!);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
print("$year is a leap year.");
} else {
print("$year is not a leap year.");
}
}
import 'dart:io';
void main() {
print("Enter a word:");
String? word = stdin.readLineSync();
String reversedWord = word!.split('').reversed.join('');
if (word == reversedWord) {
print("$word is a palindrome.");
} else {
print("$word is not a palindrome.");
}
}