š¬ Lesson 2: User Input & Interactivity
Quick Review: What We've Learned
Before diving into user input, let's quickly review what you already know!
What function starts every Dart program?
Today's Mission: "Smart Assistant CLI"
We'll build an interactive command-line assistant that:
- š¤ Greets users and remembers their name
- š§® Performs calculations on demand
- š² Generates random numbers and facts
- š Takes notes and displays them
- š Runs until the user decides to quit
Step 1
Reading User Input with stdin
š¤ How Programs "Listen" to Users
Think of your program as a conversation. You need two things:
stdout.write()
Your program "speaks" - asks questions, shows prompts
stdout.write('What is your name? ');
stdin.readLineSync()
Your program "listens" - waits for the user to type and press Enter
String? name = stdin.readLineSync();
š® Try It: Input Simulator
What is your name?
š¤ Program Response:
Waiting for input...
š§ Live Code Editor
import 'dart:io';
void main() {
stdout.write('What is your name? ');
String? name = stdin.readLineSync();
print('Hello, $name! š');
}
š What this does:
import 'dart:io';- Brings in input/output toolsstdout.write()- Asks a question (no new line)stdin.readLineSync()- Waits for you to typeString?- The ? means it might be empty/null
Step 2
Understanding Null Safety
š”ļø The Null Safety Shield
Dart protects you from "null errors" - one of the most common bugs in programming!
ā Safe: Using tryParse
int? age = int.tryParse('25');
Result: age = 25 (not null!)
Result: age = 25 (not null!)
ā ļø Handled: Null-Aware Operator
String name = stdin.readLineSync() ?? 'Guest';If input is empty, uses 'Guest' instead
ā Dangerous: Direct Parse
int age = int.parse(input);CRASHES if input isn't a number!
š® Null Safety Playground
int.parse('abc'): š„ Throws error!
int.tryParse('abc'): ā
Returns null safely
Step 3
Converting Text to Numbers
š The Number Factory
Users type text, but math needs numbers. Let's see how conversion works!
Input String
ā
int.tryParse()
āļø
ā
Output Number
42
Type: int
āļø Interactive Parser Tester
Success! 3.14 Ć 2 = 6.28
Step 4
Building Interactive Menus
š® Challenge: Input Master Quiz
Score: 0
Streak: š„ 0
Time: 0s
Loading question...
Lives:
ā¤ļøā¤ļøā¤ļø
š
Practice Projects
Apply what you've learned by building these hands-on projects.