In this blog, we will learn about how to handle user Input and Output in Dart CLI.
Introduction:
Dart is a versatile programming language known for its role in building cross-platform mobile apps with Flutter.
However, its capabilities extend far beyond mobile development, making it an excellent choice for building lightweight, efficient Command-Line Interface applications.
Whether you’re building a simple utility tool or a more complex application, handling user input and output is fundamental.
Implementation:
Getting Started with a Dart CLI Application:-
First, verify that Dart is installed on your machine. If it isn’t, download it from dart.dev. After you’ve installed it, you can create a new CLI project:
1 2 |
dart create -t console cli_application cd cli_application |
Reading User Input:-
Dart provides the stdin
object from the dart:io
library to read user input. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 |
import 'dart:io'; void main() { print('Enter your name:'); String? name = stdin.readLineSync(); // Read user input if (name != null && name.isNotEmpty) { print('Hello, $name!'); } else { print('Name cannot be empty.'); } } |
Key Points:
stdin.readLineSync()
reads input as a string.- Always check for
null
values since the user might just press Enter.
Writing Output to the Console:-
You can use the print()
function to display output in the console. For example:
1 2 3 4 |
void main() { print('Welcome to the Dart CLI Application!'); print('This application demonstrates input and output handling.'); } |
For formatted output, use string interpolation or concatenation:
1 2 3 4 5 |
void main() { String name = 'Dart Developer'; int age = 10; print('Name: $name, Age: $age'); } |
Handling Errors in User Input:-
Input validation is crucial for a robust CLI application. Here’s how to validate numeric input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import 'dart:io'; void main() { print('Enter your age:'); String? input = stdin.readLineSync(); if (input != null) { try { int age = int.parse(input); // Convert string to int print('You are $age years old.'); } catch (e) { print('Invalid input. Please enter a valid number.'); } } else { print('No input provided.'); } } |
Using Command-Line Arguments:-
Dart CLI apps can also accept arguments directly when the app is executed. Here’s an example:
1 2 3 4 5 6 7 |
void main(List<String> arguments) { if (arguments.isEmpty) { print('No arguments provided. Usage: dart app.dart <your-name>'); } else { print('Hello, ${arguments[0]}!'); } } |
Run this script with:
1 |
dart run bin/cli_application.dart Sakshi |
Conclusion:
Handling user input and output effectively is the cornerstone of creating interactive and user-friendly CLI applications.
You can explore other blogs from this site.
Thanks for reading this blog ❤️
Hope this blog helped you to better understand how to handle user Input and Output in Dart CLI.
You can check the official documentation here