šŸ’¬ Lesson 2: User Input & Interactivity

ā± 25-35 min šŸ“Š Beginner šŸ—ļø Project-Based šŸ”— Official Source
šŸ”„

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 tools
  • stdout.write() - Asks a question (no new line)
  • stdin.readLineSync() - Waits for you to type
  • String? - 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!)

āš ļø 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

šŸŽ® Live Menu Simulator

šŸŽ® 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.

šŸ“¦ Project 1 šŸ“¦ Project 2