{

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


Command line arguments read as Integer and string Dart and Flutter

Multiple ways to read input arguments Dart and flutter with examples

  • Read Command line arguments, using stdin.readLineSync(), convert try.parseIntmethod 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 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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart