💬 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
🏆
Build: Smart Assistant CLI
📋 Your Mission
Combine everything to build a complete interactive assistant!
🧩 Code Assembly Area
Drag and drop code blocks to build the complete program!
import 'dart:io';
import 'dart:math';
void main() {
bool running = true;
while (running) {
print('\n=== ASSISTANT ===');
print('1. Greet');
print('2. Calculate');
print('3. Random');
print('4. Exit');
String? choice = stdin.readLineSync();
switch (choice) {
case '1': // Greet logic
case '2': // Calculate logic
case '3': // Random logic
case '4': running = false;
}
📦 Drop code blocks here to assemble your program
🎮 Challenge: Input Master Quiz
Score: 0
Streak: 🔥 0
Time: 0s
Loading question...
Lives:
❤️❤️❤️