DEV Community

Cover image for Taking User’s Input in CLI | Scripting in Dart
Aayush Gupta
Aayush Gupta

Posted on • Updated on

Taking User’s Input in CLI | Scripting in Dart

Taking a user’s input can be sometimes a crucial thing while writing scripts to automate a job. Just like all other programming languages, dart also supports taking user’s input. Here’s how you can do that:

First of all import dart’s io (input output) library.

import ‘dart:io’;

Once imported, this library allows us to access a lot of useful classes and methods. For taking a user’s input from CLI, we need to create an instance of stdin class and use readLineSync method on it.

var line = stdin.readLineSync();

This will store the input from the user into the line variable. However, one must note that the taken inputs are always are of type String. Hence, in case you need the input in a certain type, you need to manually convert it. A nice guide on how to do that can be found here.

This method takes 2 named parameters as well which can be useful for formatting the input. First one is encoding and second one is retainNewlines.

  • Encoding is set to systemEncoding by default. You can play with it to change the encoding. Accepted encoding parameters can be checked in Encoding class.
  • retainNewlines is a boolean which is set to false by default. You can set it to true in order to append a new line at the end of the string given as input.

Example:

Here is a short example of the same method:

import 'dart:io';

main() {  
 print("Hello, What's your name?");  
 String line = stdin.readLineSync();  
 print('Hey! $line')  
}
Enter fullscreen mode Exit fullscreen mode

and that’s how you can collect user’s input from CLI. I hope this short article helped you somehow.

Top comments (0)