{

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: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example