1 / 42
Start
Future
async
Errors
API
HTTP
Stream
Listen
Types
Project
Q1
Q2
Q3
Week 3 · Day 7

Async, Streams &
Real APIs

Fetch live data. Handle errors. Listen to changes. Real apps only do this.

Future async/await try/catch HTTP JSON Streams 3 Quizzes + Project Final Dart Day!

Press J anytime to jump to any section. Arrow keys to navigate.

Recap

Where We Left Off — Day 6

You split files, used packages, formatted money. Nice.

Split Files

import, relative paths

dart:math

Random, sqrt, pi

DateTime

now, difference, format

JSON

encode/decode data

pub.dev

shared packages

intl

format money/dates

📌 Today: talk to real servers. Last Dart day before Flutter!

Topic 1 · Why Async?

Sync Code Freezes

❌ SYNC = FROZEN APP
// Fetch menu from server (takes 3s)
var menu = fetchMenu(); // ❌ blocks!
// App frozen 3 seconds 😱
// Can't click, can't scroll
print('ready');
🍳

Chef Makes One Momo

Like a chef who makes ONE momo, waits 10 min, then starts next. Kitchen frozen. Customers leave.

📌 Slow task = internet, files, database. We need: don't freeze while waiting.

Topic 1 · Compare

Sync vs Async — Visual

❌ SYNC TIMELINE
fetchMenu() [====3s====]
makeCoffee()
print done

Total: 3s + rest
App FROZEN 3s
✅ ASYNC TIMELINE
fetchMenu() [====3s====]
makeCoffee() [ok]
print done

fetchMenu runs in background
App stays responsive

📌 Sync = one at a time. Async = start slow task, continue others.

Big Picture

3 Tools for Async

Everything today uses these three.

🎁

Future

Promise of one value later.

async/await

Write async like sync.

🚰

Stream

Many values over time.

📌 Start with Future. Build up to Streams.

Topic 2 · Future

Future — Value Coming Later

🎁

Delivery Tracking Number

Like a delivery tracking number. You don't have the package yet, but you have a promise it's coming.

// Normal function — returns now
int getPrice() {
return 500;
}

// Slow function (3s)
// How to say "value coming later"?
Future<int> getPrice() {
// "int is coming later"
}

📌 Future<T> wraps a value that isn't ready yet.

Topic 2 · Future

How to Define a Future

Future<int> getPrice() async {
await Future.delayed(
Duration(seconds: 3),
);
return 500;
}
Future<int>

int will come later.

async keyword

enables await inside.

💡 Future.delayed

simulate a wait.

return 500

Dart wraps it in Future.

Topic 2 · Real Use

Fetch the Restaurant Menu

Future<String> fetchMenu() async {
print('📡 fetching...');
await Future.delayed(
Duration(seconds: 2),
);
return 'Momo, Dal Bhat, Chowmein';
}

void main() async {
print('start');
var menu = await fetchMenu();
print(menu);
print('end');
}
OUTPUT
start
📡 fetching...
(2 second wait)
Momo, Dal Bhat, Chowmein
end

Aayush writes the menu string. Sita reads it. Works like magic.

Topic 3 · async/await

async/await — Write Async Like Sync

Wait for Your Order

await says: pause here, wait for this, then continue. Like waiting for your order at a restaurant.

// Without await
var f = fetchMenu();
// f is a Future, not the value!
// With await
var menu = await fetchMenu();
// menu is the STRING now ✅

📌 async marks function. await waits for Future to complete.

Topic 3 · Rules

async/await Rules

✅ Rule 1

Use await only inside async functions.

✅ Rule 2

async function ALWAYS returns a Future.

💡 Rule 3

main() can be async too.

Future<void> greet() async { // ← async
await Future.delayed( // ← await
Duration(seconds: 1),
);
print('Namaste!');
}

void main() async { // ← main async
await greet(); // wait
print('done');
}
🎮 Quiz 1 · Async Basics

Test Your Future Knowledge

1. What does Future<int> mean?

AAn integer
BAn int that will come later
CMany integers
✅ Future<T> = a promise of a value of type T coming later.

2. await can be used where?

AAnywhere
BOnly inside async functions
COnly in main
await is only allowed inside a function marked async.

3. What does await fetchMenu() do?

AStarts and ignores
BPauses, waits for Future, returns value
CRuns synchronously
await pauses the async function until the Future completes.
Topic 4 · Errors

What If It Fails?

❌ NO SAFETY
// Network fails?
// Server down?
// JSON malformed?
var data = await fetchMenu();
// 💥 crash — app dies
🚨

Driving Without a Seatbelt

Like driving without a seatbelt. One crash = done. We need safety.

📌 Real world breaks. Always plan for failure.

Topic 4 · try/catch

Catch Errors with try/catch

try {
var menu = await fetchMenu();
print(menu);
} catch (e) {
print('Failed: $e');
}
print('keep going');
try

Risky code goes here.

catch (e)

If it breaks, handle it.

💡 App survives

Keeps running after catch.

Topic 4 · Full Safety

throw + finally

try {
if (userId.isEmpty) {
throw 'User ID required';
}
var data = await fetchUser(userId);
} catch (e) {
print('Error: $e');
} finally {
print('cleanup'); // ALWAYS runs
}
🎯 throw

Creates a custom error.

🧹 finally

Runs no matter what.

✅ Use case

Close files, stop loaders, cleanup.

Topic 4 · Real Use

Safe fetchMenu

Future<String> fetchMenu() async {
await Future.delayed(Duration(seconds: 2));

// simulate failure
if (Random().nextBool()) {
throw 'Network error';
}
return 'Momo, Dal Bhat';
}

void main() async {
try {
var menu = await fetchMenu();
print('✅ $menu');
} catch (e) {
print('❌ $e');
}
}

📌 50/50 chance of crash. App never dies. Friendly message instead.

🎮 Quiz 2 · Error Handling

Test Your Safety Skills

1. try/catch is used for?

ALoops
BHandling errors without crashing
CFunctions
✅ try/catch stops errors from killing your app.

2. finally runs when?

AOnly on success
BOnly on error
CAlways, success or error
✅ finally runs after try/catch no matter what happened.

3. throw 'bad' does what?

APrints text
BCreates an error that can be caught
CStops program
✅ throw raises an error. A matching catch can handle it.
Topic 5 · APIs

API — Ordering from a Kitchen

🍽️

You, Waiter, Kitchen

You = customer. API = waiter. Server = kitchen. You tell waiter what you want. Waiter brings food back.

// How an API call works

YOUR APP ──request──→ SERVER
←──response── (JSON)

// request: "get me /menu"
// response: { items: [...] }

📌 API = way for apps to talk to servers. Always JSON these days.

Topic 5 · Free API

Free Practice API

https://jsonplaceholder.typicode.com

GET /posts → all posts
GET /posts/1 → single post
POST /posts → create post
GET /users → all users
✅ Free

No login. No rate limit.

🎓 For learning

Fake data. Real HTTP.

📌 We'll use this to test our restaurant API calls.

Topic 5 · http package

Install the http Package

# Terminal
dart pub add http

Adds to pubspec.yaml automatically.

// In your code
import 'package:http/http.dart' as http;

as http = namespace, short alias so calls read nicely.

📌 Two steps only: pub add + import.

Topic 5 · GET

Your First GET Request

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> fetchPost() async {
var url = Uri.parse(
'https://jsonplaceholder.typicode.com/posts/1'
);

var response = await http.get(url);

print(response.statusCode); // 200
print(response.body); // JSON text
}
✅ Uri.parse(url)

Turn string into a URI.

✅ http.get()

Returns Future<Response>.

💡 .body

The response text (JSON).

Topic 5 · Parse

Parse the JSON Response

Future<void> fetchPost() async {
var url = Uri.parse(
'https://jsonplaceholder.typicode.com/posts/1'
);

var res = await http.get(url);

// JSON text → Map
var data = jsonDecode(res.body);

print(data['title']);
print(data['body']);
}

📌 Server sends text. jsonDecode turns it into a Map you can use.

Topic 5 · POST

Send Data — POST

Future<void> createPost() async {
var url = Uri.parse(
'https://jsonplaceholder.typicode.com/posts'
);

var res = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'title': 'Momo',
'body': 'Best ever',
'userId': 1,
}),
);

print(res.statusCode); // 201 (created)
}

📌 POST = send data to server. Use jsonEncode on the body.

Topic 5 · Status

Status Codes

✅ 200

OK, success.

✅ 201

Created new resource.

❌ 404

Not found.

❌ 500

Server broke.

if (res.statusCode == 200) {
// success
} else {
throw 'Failed: ${res.statusCode}';
}

📌 Memory trick: 2xx good, 4xx your fault, 5xx server fault.

Topic 6 · Streams

Stream — Many Values Over Time

❌ FUTURE NOT ENOUGH
// Future = 1 value
var price = await getPrice();
// just 500

// Live order status?
// pending → cooking → delivered
// Many values over time!
🚰

Bottle vs Tap

Future = bottle of water (one-time).
Stream = water tap (keeps flowing).

📌 Stream pushes values as they happen. Perfect for live data.

Topic 6 · Listen

Listen with .listen()

// count() returns a Stream
var stream = count();

stream.listen((value) {
print('got: $value');
});

// Output over time:
// got: 1
// got: 2
// got: 3
// got: 4
// got: 5
✅ .listen()

Start receiving values.

💡 Callback

Runs EACH time a value arrives.

✅ No await

Stream keeps pushing on its own.

Topic 6 · Create

Create with async* + yield

Stream<int> count() async* { // ← async*
for (var i = 1; i <= 5; i++) {
await Future.delayed(
Duration(seconds: 1),
);
yield i; // ← yield
}
}
✅ async*

Makes a Stream.

✅ yield

Push one value.

💡 Don't return

Yield many times instead.

📌 async + * + yield = Stream. Each yield = new value.

Topic 6 · Consume

await for — Stream in a Loop

Future<void> main() async {
await for (var n in count()) {
print('got $n');
}
print('stream done');
}
.listen()

Fire and forget. Keep running.

await for

Pause, consume values, then continue.

📌 Use await for when you want the stream done before moving on.

Topic 6 · Transform

Filter & Transform Streams

Stream<int> orders() async* {
for (var price in [300, 800, 200, 1500, 400]) {
await Future.delayed(Duration(seconds: 1));
yield price;
}
}

void main() async {
// Only big orders
var big = orders().where((p) => p > 500);

// Format them
var formatted = big.map((p) => 'Rs.$p');

await for (var order in formatted) {
print(order); // Rs.800, Rs.1500
}
}
✅ .where()

Keep only matching values.

✅ .map()

Transform each value.

✅ .take(3)

First 3 only, then stop.

Topic 6 · Types

Single vs Broadcast

🎯

Single Subscription

ONE listener only. Default type. Like a personal phone call.

var s = myStream();
s.listen(...); // ✅
s.listen(...); // ❌ error
📢

Broadcast

MANY listeners. Like a radio broadcast.

var s = myStream().asBroadcastStream();
s.listen(print); // ✅
s.listen(print); // ✅ works!

📌 UI updates = broadcast. One-time job = single.

Topic 6 · Real Use

Live Order Status

Stream<String> orderStatus() async* {
yield '⏳ Pending';
await Future.delayed(Duration(seconds: 2));
yield '🍳 Cooking';
await Future.delayed(Duration(seconds: 3));
yield '🏍️ On the way';
await Future.delayed(Duration(seconds: 4));
yield '✅ Delivered';
}

void main() async {
print('Your order:');
await for (var status in orderStatus()) {
print(status);
}
}
TIMELINE
0s: ⏳ Pending
2s: 🍳 Cooking
5s: 🏍️ On the way
9s: ✅ Delivered

Sita sees each update without refreshing. Perfect delivery UX.

Quick Compare

Future vs Stream

Future

· One value
· Gets done
· await
· Like a bottle
· return value

Stream

· Many values
· Keeps emitting
· .listen() / await for
· Like a tap
· yield each

📌 Need one thing? Future. Need updates? Stream.

🎮 Quiz 3 · Streams

Test Your Stream Skills

1. Stream vs Future?

ASame thing
BStream = many values, Future = one value
CStream is faster
✅ Future delivers one value once. Stream keeps delivering over time.

2. yield does what?

AReturns and ends
BPushes one value, continues
CCreates a Future
✅ yield pushes one value to the Stream and the function keeps running.

3. Broadcast stream allows?

ASending data out
BMultiple listeners
CFaster speed
✅ Broadcast streams can be listened to by many subscribers at once.
🎮 Project · Online Restaurant

Restaurant Gets Online

Fetch menu, handle errors, post orders, stream status. Click each feature.

📡 GET Menu
⌛ async/await
🚨 Error Handling
📤 POST Order
🚰 Live Stream
CONCEPTS USED
Quick Reference

When to Use What

One-time slow task?

→ Future + async/await

Might fail?

→ try/catch

Call a server?

→ http package + Future

Live updates?

→ Stream

Many listeners?

→ Broadcast stream

Send data?

→ http.post + jsonEncode
Summary

Today's Async Recap

Future

value coming later

async/await

pause and wait

try/catch

catch errors safely

finally

always runs

throw

custom errors

http.get

fetch data

http.post

send data

Stream

many values over time

async*/yield

create streams

Assignment

Final Take-Home: Weather App

1. Sign up at openweathermap.org for a free API key
2. Fetch weather for Kathmandu using the http package
3. Handle errors with try/catch
4. Show temp, humidity and condition
5. BONUS: stream updates every 30 seconds
6. Push to flutter-tr06 via PR

📌 Real keys, real weather, real async. This is the capstone of Dart week.

Milestone

Dart Week Complete 🎉

Seven days ago you didn't know Dart. Look at you now.

Week 1: Day 1 (Flutter intro), Day 2 (Dart basics)
Week 2: Day 3 (Lists/Fn), Day 4 (Git/Classes), Day 5 (Advanced OOP)
Week 3: Day 6 (Libraries), Day 7 (Async/API)

You know Dart. Now let's build REAL apps.

Coming Next

Flutter Next Week

Dart was the language. Flutter is what you build with.

📱

Widgets

buttons, text, images

🎨

Layouts

Row, Column, Stack

🔄

State

StatefulWidget

🧭

Navigation

screens & routes

🎨

Themes & Styles

make it pretty

🛠️

First App

real Flutter app

📌 All Dart you learned = the language. Flutter = the UI framework. Now you build.

Your Journey

7 Days — Your Progress

Day 1-2

"I don't know Dart"learned basics

Day 3-4

"Git scares me"team collaboration

Day 5-6

"Classes are hard"advanced OOP

Day 7

"API? What?"live data apps

📌 7 days ago = zero. Today = can build real apps.

Keep Going

Keep Practicing

DAILY PRACTICE
· DartPad — 15 min/day
· Build small projects
· Read others' code on GitHub
· Join Flutter Nepal community
BUILD SOMETHING
· Todo app
· Tip calculator
· Note-taking
· Simple game

📌 Pick ONE project this week. Finish it. Share it.

Thank You 🙏

Made it through 7 days of Dart.

Keep building. Ask questions. Share code.

YOUR MENTOR

Aayush Bhattarai

heyaayush.com — reach out any time.

Any Questions?

Discord: #flutter-tr06 GitHub: /flutter-tr06

Practice at dartpad.dev. Flutter next week. Come ready.