On this page24 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a Library?
- 2. dart:core Is Always There
- 3. The Core Libraries
- 4. Importing dart:math
- 5. max, min and pow
- 6. Random Numbers
- 7. Other Core Libraries
- 8. When Two Libraries Use the Same Name
- 9. Fixing a Clash with as
- 10. show and hide
- 11. Deferred Imports (A Quick Look)
- 12. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 101 — Dart Libraries
| Category | 17 — Libraries & Packages |
| Lecture | 101 of 140 |
| Estimated video length | 9 min |
| Target | Dart 3.12.2 |
| Level | Intermediate |
ListandDateTimework in every file, yetsqrtandRandomare "not found". They live in libraries you have to import — and oneimportline unlocks them.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every output and error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2. Programs that use
Random()print different numbers on every run; the others use a fixed seed so your output matches.
Prerequisites
Students should already understand, from Lectures 035–090:
- passing a function as a tear-off, and
reduceon a list (Lectures 035 and 044) - importing another file with
import 'bank_account.dart';(Lecture 057) - that privacy with
_is per file (Lecture 057) - extensions and their names (Lecture 069)
import 'dart:async';forTimeoutException(Lecture 090)
Connection With Previous Lectures
In Lecture 044 we found the biggest mark with reduce, because lists have no .max. Now Sara
wants the square root of a number:
void main() {
print(sqrt(16));
}Error: Method not found: 'sqrt'.
print(sqrt(16));
^^^^Dart has a sqrt function — it just isn't visible in this file. To use it, we need to know
where Dart keeps its tools and how to bring them in.
Learning Objectives
By the end of this lecture you will be able to:
- Explain what a library is in Dart
- Recognize the core libraries
dart:core,dart:math,dart:async,dart:io,dart:convertanddart:collection - Import a library with
import 'dart:math'; - Use
sqrt,pi,max,min,powandRandom - Read a name-clash error and fix it with an
asprefix - Limit what an import brings in with
showandhide - Recognize the error messages Dart produces for common import mistakes
1. What Is a Library?
A library is a collection of code — functions, classes, constants — that other code can
use. In Dart, every .dart file is a library. That is why privacy with _ works per file
(Lecture 057): a private name stays inside its own library.
Analogy — think of a school with many rooms. Each room (library) has its own tools. To use the science lab's microscope, you first go to the science lab: that is an
import.
2. dart:core Is Always There
Dart ships with core libraries whose names start with dart:. One of them, dart:core,
is imported into every file automatically. It holds print, int, String, List, Map,
DateTime and everything you have used so far:
void main() {
var exam = DateTime(2026, 10, 17);
var marks = <int>[80, 75];
print(exam.year);
print(marks.length);
print(int.parse('42') + 1);
}2026
2
43No import line — yet every name works.
3. The Core Libraries
Everything else needs an import. These are the core libraries you will meet most:
| Library | What it holds | Where we use it |
|---|---|---|
dart:core | numbers, strings, lists, print — imported automatically | every lecture |
dart:math | sqrt, pi, max, min, pow, Random | this lecture |
dart:async | TimeoutException, Completer, StreamController | Lectures 090–096 |
dart:io | files, folders, the console, the operating system | Lectures 106–107 |
dart:convert | JSON and text encodings | Lecture 108 |
dart:collection | extra collections such as Queue | below |
4. Importing dart:math
Write import with the library name in quotes, at the very top of the file:
import 'dart:math';
void main() {
print(sqrt(16));
print(pi);
}4.0
3.141592653589793sqrt and pi are now visible. sqrt always returns a double, so 16 gives 4.0.
5. max, min and pow
dart:math also compares and raises numbers:
import 'dart:math';
void main() {
print(max(80, 95));
print(min(80, 95));
print(pow(2, 10));
}95
80
1024max and min take exactly two numbers. For a whole list, pass max as a tear-off to
reduce (Lectures 035 and 044):
import 'dart:math';
void main() {
var marks = [72, 95, 64, 88];
print(marks.reduce(max));
print(marks.reduce(min));
}95
64A ready-made .max and .sum on lists comes from a package, which we meet in Lecture 103 —
Dart Packages.
6. Random Numbers
Random makes random numbers. nextInt(6) gives 0 to 5, so add 1 for a dice roll:
import 'dart:math';
void main() {
var random = Random();
var dice = random.nextInt(6) + 1;
print('Ali rolled $dice');
}Ali rolled 2Run it again and you get another number. Give Random a seed — Random(42) — and it
produces the same sequence every run, which is useful for testing:
import 'dart:math';
void main() {
var random = Random(42);
print(random.nextInt(6) + 1);
print(random.nextInt(6) + 1);
print(random.nextInt(6) + 1);
}2
1
17. Other Core Libraries
Several imports can sit together. Here are three more core libraries at work:
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
void main() {
print(jsonEncode({'name': 'Sara', 'marks': 88}));
var line = Queue<String>();
line.add('Ali');
line.add('Sara');
line.addFirst('Zayan');
print(line);
stdout.write('Hello, ');
stdout.writeln('Dart!');
}{"name":"Sara","marks":88}
{Zayan, Ali, Sara}
Hello, Dart!jsonEncode turns a map into JSON text, a Queue adds and removes at both ends, and
stdout.write prints without starting a new line. We will study JSON in Lecture 108 and
files with dart:io in Lecture 106.
8. When Two Libraries Use the Same Name
Ali and Sara each wrote a helper file, and both named their function describe:
// ali_tools.dart
String describe(int marks) => marks >= 50 ? 'Pass' : 'Fail';// sara_tools.dart
String describe(int marks) => 'Marks: $marks';
extension ShoutTools on String {
String shout() => toUpperCase();
}Import both, and Dart cannot know which describe you mean:
import 'ali_tools.dart';
import 'sara_tools.dart';
void main() {
print(describe(72));
}Error: 'describe' is imported from both 'ali_tools.dart' and 'sara_tools.dart'.
print(describe(72));
^^^^^^^^Writing helper files like these is the topic of Lecture 102 — Creating Your Own Libraries.
9. Fixing a Clash with as
as gives a library a prefix. Its names are then reached through that prefix, like a
surname:
import 'ali_tools.dart';
import 'sara_tools.dart' as sara;
void main() {
print(describe(72));
print(sara.describe(72));
}Pass
Marks: 72Many programmers prefix dart:math too, so math.max reads clearly:
import 'dart:math' as math;
void main() {
print(math.max(72, 95));
print(math.sqrt(81));
}95
9.010. show and hide
show imports only the names you list. hide imports everything except them:
import 'ali_tools.dart';
import 'sara_tools.dart' hide describe;
void main() {
print(describe(72));
print('sara'.shout());
}Pass
SARAhide describe removed the clash, while ShoutTools still arrived. Names work for extensions
too — this is how you hide an extension (Lecture 069): import 'sara_tools.dart' hide ShoutTools;. With show, a name you did not list is simply missing:
import 'dart:math' show sqrt, pi;
void main() {
print(sqrt(25));
print(pi);
}5.0
3.141592653589793Calling max here would give Error: Method not found: 'max'.
11. Deferred Imports (A Quick Look)
You may see import 'reports.dart' deferred as reports;. It loads a library only when the
program asks for it, mainly so web apps start faster. You won't need it in this course — just
recognize it.
12. A Real-World Example
A class result summary that uses a prefix, show, and a seeded lucky draw:
import 'dart:convert' show jsonEncode;
import 'dart:math' as math;
void main() {
var marks = {'Ali': 72, 'Sara': 95, 'Zayan': 64, 'Hina': 88};
var values = marks.values.toList();
var highest = values.reduce(math.max);
var lowest = values.reduce(math.min);
var names = marks.keys.toList();
var winner = names[math.Random(7).nextInt(names.length)];
print('Highest: $highest, Lowest: $lowest');
print('Lucky draw: $winner');
print(jsonEncode({'highest': highest, 'lowest': lowest, 'winner': winner}));
}Highest: 95, Lowest: 64
Lucky draw: Ali
{"highest":95,"lowest":64,"winner":"Ali"}math. shows at a glance which names come from dart:math, and show jsonEncode brings in
just the one function we need.
Code Examples
Example 1 — dart:core Needs No Import
void main() {
var name = 'Zayan';
var age = int.parse('6');
print('$name is $age');
print(name.toUpperCase());
}Zayan is 6
ZAYANExample 2 — Area of a Circle
import 'dart:math';
void main() {
var radius = 7;
var area = pi * radius * radius;
print('Area: ${area.toStringAsFixed(2)}');
}Area: 153.94Example 3 — max, min, pow
import 'dart:math';
void main() {
print(max(-3, 8));
print(min(4.5, 2.5));
print(pow(5, 3));
}8
2.5
125Example 4 — Seeded Dice
import 'dart:math';
void main() {
var random = Random(3);
for (var i = 1; i <= 3; i++) {
print('Roll $i: ${random.nextInt(6) + 1}');
}
}Roll 1: 2
Roll 2: 6
Roll 3: 5Example 5 — An as Prefix
import 'dart:math' as math;
void main() {
var side = math.sqrt(49);
print('Side: $side');
print('Bigger: ${math.max(side, 6.5)}');
}Side: 7.0
Bigger: 7.0Example 6 — show Only What You Need
import 'dart:math' show pow, sqrt;
void main() {
var a = 6;
var b = 8;
var c = sqrt(pow(a, 2) + pow(b, 2));
print('Hypotenuse: $c');
}Hypotenuse: 10.0Example 7 — Student Marks
import 'dart:math' as math;
void main() {
var marks = [55, 91, 78, 66];
var best = marks.reduce(math.max);
var worst = marks.reduce(math.min);
print('Best: $best');
print('Worst: $worst');
print('Gap: ${best - worst}');
}Best: 91
Worst: 55
Gap: 36How it works
math.maxis passed toreduceas a tear-off — no parentheses.reducekeeps the bigger of each pair, ending with91.- The same works with
math.minfor the lowest mark.
Example 8 — Shopping Total as JSON
import 'dart:convert' show jsonEncode;
void main() {
var cart = {'Notebook': 500, 'Pen': 50, 'Bag': 1500};
var total = cart.values.reduce((a, b) => a + b);
print(jsonEncode({'items': cart.length, 'total': total}));
}{"items":3,"total":2050}How it works
dart:coregives the map andreduce; no import is needed for them.show jsonEncodeimports a single function fromdart:convert.jsonEncodewrites keys in double quotes, as JSON requires.
Example 9 — Bank Balance with Interest
import 'dart:math' as math;
void main() {
var balance = 1000;
var rate = 0.05;
var years = 3;
var result = balance * math.pow(1 + rate, years);
print('After $years years: ${result.toStringAsFixed(2)}');
}After 3 years: 1157.63How it works
- Each year multiplies the balance by
1.05; three years is1.05to the power3. math.pow(1.05, 3)is about1.157625.toStringAsFixed(2)rounds to cents:1157.63.
Example 10 — Last Three Temperatures
import 'dart:collection';
void main() {
var readings = Queue<double>();
for (var t in [29.5, 31.0, 30.5, 32.0]) {
readings.add(t);
if (readings.length > 3) readings.removeFirst();
}
print(readings);
}{31.0, 30.5, 32.0}How it works
Queuecomes fromdart:collection.- Each new reading joins at the back with
add. - Once there are more than three,
removeFirstdrops the oldest, so only the latest three remain.
Common Beginner Mistakes
1. Forgetting the import
void main() {
// print(sqrt(16)); // ✗ without import 'dart:math'
}Error: Method not found: 'sqrt'.2. Putting import below other code
void main() {
print('x');
}
// import 'dart:math'; // ✗ must be at the topError: Directives must appear before any declarations.
Try moving the directive before any declarations.3. Leaving out the quotes
// import dart:math; // ✗Error: Expected a String, but got 'dart'.The library name is a string: import 'dart:math';.
4. Misspelling the library
// import 'dart:maths'; // ✗Error: Dart library 'dart:maths' is not available on this platform.5. Adding a prefix, then forgetting it
import 'dart:math' as math;
void main() {
// print(sqrt(4)); // ✗
print(math.sqrt(4));
}Error: Method not found: 'sqrt'.With as math, every name needs math. in front.
6. Expecting your own name to clash with dart:math
If your file marks_tools.dart defines a max and you also import dart:math, Dart does
not report a clash — your max quietly wins over the dart: one. A clash error appears
only between two of your own libraries (or two dart: ones). Use a prefix to be clear about
which one you call.
Best Practices
- Put all imports at the top,
dart:imports first, in alphabetical order. - Import only the libraries you use;
dart analyzewarns about unused imports. - Prefix libraries whose names are short or common, such as
import 'dart:math' as math;. - Use
showwhen you need one or two names from a big library. - Use
hideto remove a single clashing name. - Seed
Randomwhile testing; drop the seed for real randomness.
Mini Challenge
Zayan rolls two dice with Random(7) from a prefixed dart:math. Print both rolls, their
total, and the higher roll using max.
Your program should print exactly:
Rolls: 5 and 6
Total: 11
Higher: 6Try it yourself before opening the solution.
Show solution
import 'dart:math' as math;
void main() {
var random = math.Random(7);
var first = random.nextInt(6) + 1;
var second = random.nextInt(6) + 1;
print('Rolls: $first and $second');
print('Total: ${first + second}');
print('Higher: ${math.max(first, second)}');
}Rolls: 5 and 6
Total: 11
Higher: 6How it works
math.Random(7)always produces the same sequence, so the rolls are5and6.math.maxpicks the higher of the two.
Practice Questions
Work through these in order — they run from beginner to application to challenge.
Beginner
- Import
dart:mathand print the square root of144. - Print
pirounded to two decimal places. - Print the larger and the smaller of
15and40usingmaxandmin.
Application
-
Print the area of a circle with radius
10, rounded to two decimals. -
Import
dart:mathwith the prefixmathand print3to the power4. -
Import only
sqrtwithshow, and print the square root of2.25. -
For the marks
[48, 83, 97, 61], print the highest and lowest withreduce. -
This program does not compile. Fix it in two different ways:
import 'dart:math' as math; void main() { print(sqrt(49)); }
Challenge
- Sara saves
2000at10%interest per year for2years. Usepowto printBalance: 2420.00. - Using
Random(42), draw five lucky numbers from1to100into a list. Print the list and the biggest number.
Practice Answers
Question 1 — Solution
import 'dart:math';
void main() {
print(sqrt(144));
}12.0Question 2 — Solution
import 'dart:math';
void main() {
print(pi.toStringAsFixed(2));
}3.14Question 3 — Solution
import 'dart:math';
void main() {
print(max(15, 40));
print(min(15, 40));
}40
15Question 4 — Solution
import 'dart:math';
void main() {
var area = pi * 10 * 10;
print(area.toStringAsFixed(2));
}314.16Question 5 — Solution
import 'dart:math' as math;
void main() {
print(math.pow(3, 4));
}81Question 6 — Solution
import 'dart:math' show sqrt;
void main() {
print(sqrt(2.25));
}1.5Question 7 — Solution
import 'dart:math';
void main() {
var marks = [48, 83, 97, 61];
print(marks.reduce(max));
print(marks.reduce(min));
}97
48Question 8 — Solution
Either add the prefix to the call, or remove the prefix from the import:
import 'dart:math' as math;
void main() {
print(math.sqrt(49));
}import 'dart:math';
void main() {
print(sqrt(49));
}Both print:
7.0Question 9 — Solution
import 'dart:math';
void main() {
var balance = 2000 * pow(1.10, 2);
print('Balance: ${balance.toStringAsFixed(2)}');
}Balance: 2420.00Question 10 — Solution
import 'dart:math';
void main() {
var random = Random(42);
var lucky = [for (var i = 0; i < 5; i++) random.nextInt(100) + 1];
print(lucky);
print('Biggest: ${lucky.reduce(max)}');
}[88, 59, 5, 86, 78]
Biggest: 88The seed makes the draw repeatable; without it, every run gives new numbers.
Quick Revision
- What is a library in Dart?
- Which core library is imported automatically?
- Where must
importlines go? - Which library holds
sqrt,piandRandom? - How many numbers do
maxandmintake? - What does
asdo in an import? - What is the difference between
showandhide? - Why would you give
Randoma seed?
Key Takeaways
- Every Dart file is a library; privacy with
_is per library. dart:coreis imported automatically; otherdart:libraries needimport.dart:mathgivessqrt,pi,max,min,powandRandom.- Imports go at the top of the file, with the library name in quotes.
- Two imports with the same name cause an error; an
asprefix separates them. showimports only the listed names;hideimports all but them — extensions included.deferred asloads a library later; you only need to recognize it.
What's Next?
Lecture 102 — Creating Your Own Libraries. Ali's and Sara's helper files were libraries too. Next we will build our own multi-file libraries on purpose — splitting code into files, choosing what each file makes public, and importing them cleanly.