1 / 38
Start
OwnFiles
dart:math
DateTime
parse
convert
pub.dev
pubspec
Q1
Q2
Q3
Project
Week 3 · Day 6

Libraries & Packages

Use code others already wrote. Save hours. Build real apps.

Split Files dart:math dart:convert DateTime int.parse pub.dev pubspec.yaml 3 Quizzes + Project

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

Recap

Where We Left Off — Day 5

Quick reminder of everything you already know.

Modifiers

abstract, base, interface, final

abstract

force children to fill methods

sealed

fixed family + exhaustive switch

factory

smart object creation

mixins

share skills with with

extensions

add methods to built-ins

📌 Today: stop rewriting. Use existing code.

Topic 1 · Why Libraries?

One Big File = Chaos

❌ MEGA FILE
// main.dart — 2000 lines 😱
class MenuItem { ... }
class Order { ... }
class Payment { ... }
class Bill { ... }
// scroll forever
// can't find anything
// team fights over same file
📚

One Giant Book

Like one book with ALL subjects. Math, science, history mixed. Can't find anything.

📌 Break big file into small files. Each file = one topic.

Topic 1 · Solution

Split into Small Files

restaurant/
├── menu.dart ← menu code only
├── order.dart ← order code only
├── bill.dart ← bill code only
└── main.dart ← uses all 3
📑

Chapters in a Book

Like chapters in a book. Math chapter, science chapter. Find fast, organize easy.

📌 One concept = one file. One folder = one feature.

Big Picture

3 Types of Libraries

Every import is one of these three.

📁

Your Own Files

Files YOU write and split.

import 'menu.dart';
🧰

Dart Core

Already in Dart — FREE.

import 'dart:math';
🌐

pub.dev Packages

Shared by other devs.

import 'package:http/http.dart';

📌 We'll cover all 3. Starting with your own files.

Topic 2 · Your Files

Split Your Own Files

❌ GROWING FILE
// main.dart — getting big
List<String> menuItems = [...];
class Order { ... }
class Bill { ... }

// hard to find, hard to edit
🗃️

Folders on Your Laptop

Like moving files to folders on your computer. One topic per folder.

📌 Rule: one concept = one file.

Topic 2 · Your Files

How to Split Files

❌ BEFORE
// main.dart
class MenuItem {
final String name;
final int price;
MenuItem(this.name, this.price);
}

void main() {
var m = MenuItem('Momo', 120);
}
// menu.dart — NEW file
class MenuItem {
final String name;
final int price;
MenuItem(this.name, this.price);
}
// main.dart
import 'menu.dart'; // ← import it!

void main() {
var m = MenuItem('Momo', 120);
}
Topic 2 · import

importTwo Ways

Relative path

// same folder
import 'menu.dart';

// subfolder
import 'data/menu.dart';

// parent folder
import '../utils/helpers.dart';

Package path

// uses app name from
// pubspec.yaml
import 'package:restaurant/menu.dart';

📌 Small project → use relative. Big project → use package path.

Topic 2 · Real Use

Real Use — Restaurant Files

restaurant/
├── pubspec.yaml
├── lib/
│ ├── menu.dart
│ ├── order.dart
│ ├── bill.dart
│ └── main.dart
// menu.dart
class MenuItem {
final String name;
final int price;
MenuItem(this.name, this.price);
}

var menu = [
MenuItem('Momo', 120),
MenuItem('Dal Bhat', 150),
];
// main.dart
import 'menu.dart';

void main() {
for (var item in menu) {
print('${item.name} Rs.${item.price}');
}
}
🎮 Quiz 1 · Your Files

Test Your Import Knowledge

1. import 'menu.dart'; — what does it do?

ADeletes menu.dart
BLoads code from menu.dart
CCopies the file
✅ import loads the classes/functions from that file so you can use them here.

2. Why split one file into many?

AFaster compile
BEasier to find, edit, share
CSaves memory
✅ Small files are easy to navigate and teams don't fight over one giant file.

3. import '../utils.dart'; means?

ASame folder
BParent folder
CSubfolder
.. goes up one folder. Just like the terminal!
Topic 3 · Dart Core

Dart Core — Already Included

🧰

Toolbox that comes with Dart

Hammer, screwdriver already inside. No buying. Just import 'dart:xxx'; and use.

🎲 dart:math

Random, sqrt, pi

📝 dart:convert

JSON, Base64

⏰ dart:core

String, int (auto-imported)

📂 dart:io

files, network

⚡ dart:async

Future, Stream (Day 7)

🗃️ dart:collection

extra collections

📌 Just import 'dart:xxx'; — free, always there.

Topic 3.1 · dart:math

dart:math — Random Numbers

❌ PROBLEM
// Want a random order ID 1..1000
// Dart core has no Random() by default!
var id = ??? // how?
🎲

A Dice

Like a dice. Roll → random number. dart:math gives you the dice.

📌 Random, sqrt, pi, pow — all need import 'dart:math';

Topic 3.1 · dart:math

How to Use dart:math

import 'dart:math'; // ← import

var rng = Random(); // create generator

rng.nextInt(100); // 0 to 99
rng.nextDouble(); // 0.0 to 1.0
rng.nextBool(); // true / false

✅ Do

Create Random() once, reuse.

💡 Note

nextInt(100) → 0..99 (not including 100).

✅ Also

Has sqrt, pi, pow, min, max.

Topic 3.1 · Real Use

Real Use — Order IDs

import 'dart:math';

String generateOrderId() {
var rng = Random();
var num = rng.nextInt(10000);
return 'ORD-$num';
}

int rollDice() => Random().nextInt(6) + 1;

void main() {
print(generateOrderId()); // ORD-4823
print(rollDice()); // 1..6
print(sqrt(16)); // 4.0
print(pi); // 3.14159...
}
Topic 3.2 · DateTime

DateTime — Time Travel

❌ PROBLEM
// When was the order placed?
// No time tracking = can't sort
// Can't show "2 hours ago"
📅

Clock + Calendar

Like a clock + calendar together. Knows current time + date.

📌 DateTime is auto-imported from dart:core. Free!

Topic 3.2 · DateTime

How to Use DateTime

var now = DateTime.now();
print(now); // 2026-04-21 14:30:00

now.hour; // 14
now.day; // 21
now.month; // 4
now.year; // 2026
now.weekday; // 2 (Tuesday)

// specific date
var bday = DateTime(2001, 5, 15);

// difference
var diff = now.difference(bday);
print(diff.inDays); // days between

✅ Do

DateTime.now() for current time.

💡 Note

weekday: 1 = Mon, 7 = Sun.

✅ Also

.difference() returns a Duration.

Topic 3.2 · Real Use

Real Use — Order Timestamp

class Order {
final String id;
final DateTime placedAt;

Order(this.id) : placedAt = DateTime.now();

String get timeInfo {
var hour = placedAt.hour;
var minute = placedAt.minute;
return '$hour:$minute';
}
}

void main() {
var o = Order('ORD-100');
print(o.timeInfo); // 14:30
}
Topic 3.3 · parse

int.parse — String to Number

❌ PROBLEM
// User types '500' (as text!)
String input = '500';

input + 10; // ❌ '50010' (concats!)
input * 2; // ❌ error
🔄

Translator

'500' is a word. int.parse turns it into a number you can add, multiply, tax.

Topic 3.3 · parse

How to Parse

// String → int
int x = int.parse('500');
print(x + 10); // 510 ✅

// String → double
double y = double.parse('99.5');
print(y * 2); // 199.0

// number → String
int price = 120;
String s = price.toString();
print(s + ' rupees'); // '120 rupees'

✅ Works

int.parse('500') → 500.

❌ Breaks

int.parse('abc') → crashes.

💡 Safer

int.tryParse('abc') → null.

Topic 3.3 · Real Use

Real Use — Tax Calculator

void takeInput(String userInput) {
var price = int.tryParse(userInput);

if (price == null) {
print('❌ Not a number');
return;
}

print('Price is Rs.$price');
print('With 13% tax: Rs.${price * 1.13}');
}

void main() {
takeInput('500'); // ✅ Price is Rs.500
takeInput('abc'); // ❌ Not a number
}
Topic 3.4 · dart:convert

dart:convert — Save Data as Text

❌ PROBLEM
var order = {
'id': 'ORD-1',
'items': ['Momo', 'Tea'],
'total': 150,
};
// Want to save to file or
// send over internet
// Need to turn it into TEXT
📝

Packing a Box

Like packing a box for shipping. Fold the object flat into text. Unpack later.

📌 JSON = standard text format for data. Used everywhere on the web.

Topic 3.4 · Real Use

Real Use — JSON Round Trip

import 'dart:convert';

void main() {
var order = {
'id': 'ORD-1',
'items': ['Momo', 'Tea'],
'total': 150,
};

// Map → JSON text
String text = jsonEncode(order);
print(text);
// {"id":"ORD-1","items":["Momo","Tea"],"total":150}

// JSON text → Map
var back = jsonDecode(text);
print(back['items']); // [Momo, Tea]
}

📌 jsonEncode → text. jsonDecode → Map. Round trip!

🎮 Quiz 2 · Dart Core

Test Your Core Library Knowledge

1. Random().nextInt(10) returns?

A1 to 10
B0 to 9
C0 to 10
nextInt(n) returns 0 up to but not including n.

2. int.parse('abc') does?

Areturns 0
Bcrashes
Creturns null
int.parse throws on bad input. Use int.tryParse if unsure.

3. Why use jsonEncode?

AEncrypt data
BTurn Map into text
CMake it faster
✅ JSON is text — perfect for saving to a file or sending over the network.
Topic 4 · pub.dev

pub.dev — Shared Code Store

❌ REINVENTING
// Want: format 15000 as "15,000"
// Build from scratch?
// Handle 1 lakh, 1 crore too?
// Hours of work 😱
🏪

Supermarket for Code

Like a supermarket for code. Someone already built it. Grab and use. Free.

📌 pub.dev has 100k+ packages. Someone already solved your problem.

Topic 4 · pub.dev

What pub.dev Looks Like

pub.dev
──────────────────────
📦 http — web requests
📦 intl — formatting
📦 shared_prefs — save settings
📦 provider — state mgmt
📦 dio — advanced http

Visit It

https://pub.dev

// Search for:
"http"
"intl"
"image picker"

Every Flutter dev lives here.

Topic 4 · pubspec.yaml

pubspec.yaml — The Recipe

name: restaurant # your app name
description: A demo app
version: 1.0.0

environment:
sdk: ">=3.0.0 <4.0.0"

dependencies:
intl: ^0.19.0 # ← package!
http: ^1.2.0 # ← another!

dev_dependencies:
test: ^1.24.0 # only for testing

✅ Do

List packages under dependencies.

💡 Note

^1.0.0 = compatible updates allowed.

✅ After edit

Run dart pub get.

Topic 4 · Install

How to Install a Package

Step 1

# Terminal
dart pub add intl

Adds intl to pubspec.yaml.

Step 2

# Auto after pub add
dart pub get

Downloads package.

Step 3

// in .dart file
import 'package:intl/intl.dart';

Use it!

📌 3 steps. Takes 10 seconds. Saves you hours.

Topic 4 · Real Use

Real Use — Format Money

import 'package:intl/intl.dart';

void main() {
var price = 15000;

// Without intl:
print(price); // 15000

// With intl:
var f = NumberFormat('#,###');
print(f.format(price)); // 15,000

// Nepali rupees
var rs = NumberFormat.currency(
symbol: 'Rs.',
);
print(rs.format(15000)); // Rs.15,000.00
}
Topic 4 · Versions

Version ^1.0.0 Meaning

intl: ^1.2.3
│ │ │
│ │ └─ PATCH (tiny fixes)
│ └─── MINOR (new features)
└───── MAJOR (breaking)

^1.2.3

Means 1.2.3 up to <2.0.0.

💡 Safe

Auto-updates that won't break your app.

🔒 Lock

Use 1.2.3 (no caret) to pin exactly.

Topic 4 · Popular

Popular Packages

🌐 http

make web requests

🎨 flutter/material

UI widgets

💾 shared_preferences

save settings

📸 image_picker

pick photos

📍 geolocator

GPS location

🔔 notifications

push notifs

📌 Need something? Search pub.dev FIRST. Don't reinvent.

🎮 Quiz 3 · Packages

Test Your pub.dev Knowledge

1. What is pub.dev?

ADart docs
BStore of shared packages
CGitHub
✅ pub.dev hosts 100k+ open-source packages for Dart and Flutter.

2. ^1.2.0 allows?

AOnly 1.2.0
B1.2.0 up to <2.0.0
CAny version
✅ Caret lets minor + patch updates. Major bump is blocked (breaking changes).

3. Where do you list packages?

Amain.dart
Bpubspec.yaml dependencies
Cimport line
✅ pubspec.yaml is the recipe. The dependencies section is where packages live.
🎮 Project · Upgraded Restaurant

Build the Full Restaurant

Everything from today — split files, dart:math, DateTime, JSON, intl. Click each feature.

📁 Split Files
🎲 Random ID
📅 DateTime
📝 JSON
💵 intl
CONCEPTS USED
Quick Reference

When to Use What

Save code organized?

→ split files

Random number?

→ dart:math

Current time?

→ DateTime

String → number?

→ int.parse

Save as text?

→ jsonEncode

Format money?

→ intl package

Web request?

→ http package

Save settings?

→ shared_preferences
Summary

Today's Libraries Recap

Split Files

import, relative paths

dart:math

Random, sqrt, pi

DateTime

now, difference, format

int.parse

String → number

dart:convert

jsonEncode/Decode

pub.dev

shared packages

pubspec.yaml

list packages

^version

safe updates

intl

format money/dates

Assignment

Take-Home: Polish Restaurant

1. Split restaurant into 4 files: menu.dart, order.dart, bill.dart, main.dart
2. Add random order IDs using dart:math
3. Store DateTime on each Order
4. Save the order as JSON with dart:convert
5. Format all prices with the intl package
6. Push to GitHub via PR

Use branches! Create feature/your-name and submit a PR.

Coming Next

Day 7 — Async & Futures

await async Future Stream http package

We'll make a real API call and get live data back. Finish today's assignment first!

Cheat Sheet

Dart Commands

dart create myapp # new project
dart run # run main.dart
dart pub add <name> # add package
dart pub get # download packages
dart pub upgrade # update versions
dart format . # format code
dart analyze # find issues

📌 Save this slide. You'll use these commands every day.

Any Questions?

Practice at dartpad.dev — add import lines at the top to pull in packages!