{

How to read input arguments from console Dart| Read a string from the console command line from a program


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 console
  • stdin - 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example