Read Time:1 Minute, 18 Second
Dart – Input & Output
In Dart, you can take input from the user by using .readLineSync()
function from stdin
class. To take input from the console you need to import a library, named dart:io
from libraries of Dart.
Taking a String Input from a User
// importing dart:io file
import 'dart:io';
void main()
{
print("Whats your name pal?");
// Reading user Input
String name = stdin.readLineSync();
// Printing the name
print("Hello, $name! \n, Nice to meet you!");
}
Input: Fallenblood
Output:
Whats your name pal?
Hello, Fallenblood!
Nice to meet you!
Taking Int as Input
// importing dart:io file
import 'dart:io';
void main()
{
print("Enter your age!");
// Reading user Input
int age = int.parse(stdin.readLineSync());
// Printing
print("Your age is, $age);
}
Input: 21
Output:
Enter your age!
Your age is, 21
NOTE: stdin.readLineSync
takes input as a string, in order to get an integer or whole number you need to convert a string into an integer by int.parse() function.
Taking Double as Input
// importing dart:io file
import 'dart:io';
void main()
{
print("Enter a decimal number!");
// Reading user Input
int decimalnum = double.parse(stdin.readLineSync());
// Printing
print(decimalnum);
}
Input: 2.1
Output:
2.1
NOTE: stdin.readLineSync
takes input as a string, in order to get a decimal number you need to convert a string into a double by double.parse()
function.
OUTPUT
In Dart, you can print something by print
function.
print("YO! I can print anything , not everything!");
In the next lesson, you will learn about Comments.
[…] Input & Output […]
[…] In the next lesson, you will learn about Input&Output. […]