A Simple Interactive Program
Explore how to write a basic Dart application that reads user input synchronously from the console and displays a personalized greeting. Understand how to safely handle nullable input using Dart's null-aware operators and the role of the dart:io library in non-web applications. This lesson builds foundational skills for creating interactive command-line tools and prepares you for more advanced user input handling in Flutter.
We'll cover the following...
We often encounter scenarios where we need to take input from a user and print that input onto the console. Let us write a program for a personalized greeting application. The program will ask for a name and then display a personalized greeting based on the input.
The following program requires input from the user to execute successfully. After running the program, the console waits for text to be typed and the Enter key to be pressed.
import 'dart:io';
void main() {
print('Please enter your name:');
final name = stdin.readLineSync();
final safeName = name ?? 'there';
print('Hello $safeName');
}Line 1: We import the
dart:iolibrary. In computer ...