How to read input arguments from console Dart| Read a string from the console command line from a program
Multiple ways to read input arguments Dart and flutter with examples
- Read Command line arguments, using
stdin.readLineSync()
, converttry.parseInt
method to convert as Integer. - Read arguments as a string, use
stdin.readLineSync()
This tutorial shows multiple ways to read the console arguments or input parameters from a user in the Dart program.
How to read input arguments from Console Command in Dart?
dart:io
package provides two classes.
stdout
- contains methods to print the string to consolestdin
- Contains methods to read input from the console
stdin.readLineSync()
method read the input from the stdin console. It returns an optional String, which can be null and read as a String until Enter key is pressed.
Syntax:
String? readLineSync(
{Encoding encoding = systemEncoding, bool retainNewlines = false})
Encoding
parameter to provide encoding retainNewlines
, boolean value to indicate whether string stores End of line character or not.
Here is a program to read input from the console.
import 'dart:io';
void main() {
stdout.write("Please enter Name : ");
var inputName = stdin.readLineSync();
stdout.write(inputName);
}
Output:
Please enter Name : john
john
How to get integer input from the user in a dart program?
stdin.readLineSync()
return the string.
Parse the string to int using try.tryParse()
method.
You can check Multiple ways to convert the string into int.
Here is a sample example program to read a number from the input console.
import 'dart:io';
void main() {
stdout.write("Please enter Name : ");
var inputName = stdin.readLineSync();
stdout.write("Please enter Age : ");
var age = int.tryParse(stdin.readLineSync());
stdout.write(inputName);
stdout.write('\n');
stdout.write(age);
}
Please enter Name : john
Please enter Age : 25
john
25
Conclusion
Learned how to read input data from the user in the terminal console in dart and flutter.