Watch the video (9 min)
On this page24 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a Library?
  5. 2. dart:core Is Always There
  6. 3. The Core Libraries
  7. 4. Importing dart:math
  8. 5. max, min and pow
  9. 6. Random Numbers
  10. 7. Other Core Libraries
  11. 8. When Two Libraries Use the Same Name
  12. 9. Fixing a Clash with as
  13. 10. show and hide
  14. 11. Deferred Imports (A Quick Look)
  15. 12. A Real-World Example
  16. Code Examples
  17. Common Beginner Mistakes
  18. Best Practices
  19. Mini Challenge
  20. Practice Questions
  21. Practice Answers
  22. Quick Revision
  23. Key Takeaways
  24. What's Next?

Lecture 101 — Dart Libraries

Category17 — Libraries & Packages
Lecture101 of 140
Estimated video length9 min
TargetDart 3.12.2
LevelIntermediate

print, List and DateTime work in every file, yet sqrt and Random are "not found". They live in libraries you have to import — and one import line 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 reduce on 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'; for TimeoutException (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:

dart
void main() {
  print(sqrt(16));
}
output
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:convert and dart:collection
  • Import a library with import 'dart:math';
  • Use sqrt, pi, max, min, pow and Random
  • Read a name-clash error and fix it with an as prefix
  • Limit what an import brings in with show and hide
  • 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:

dart
void main() {
  var exam = DateTime(2026, 10, 17);
  var marks = <int>[80, 75];
  print(exam.year);
  print(marks.length);
  print(int.parse('42') + 1);
}
output
2026
2
43

No import line — yet every name works.


3. The Core Libraries

Everything else needs an import. These are the core libraries you will meet most:

LibraryWhat it holdsWhere we use it
dart:corenumbers, strings, lists, print — imported automaticallyevery lecture
dart:mathsqrt, pi, max, min, pow, Randomthis lecture
dart:asyncTimeoutException, Completer, StreamControllerLectures 090–096
dart:iofiles, folders, the console, the operating systemLectures 106–107
dart:convertJSON and text encodingsLecture 108
dart:collectionextra collections such as Queuebelow

4. Importing dart:math

Write import with the library name in quotes, at the very top of the file:

dart
import 'dart:math';

void main() {
  print(sqrt(16));
  print(pi);
}
output
4.0
3.141592653589793

sqrt 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:

dart
import 'dart:math';

void main() {
  print(max(80, 95));
  print(min(80, 95));
  print(pow(2, 10));
}
output
95
80
1024

max and min take exactly two numbers. For a whole list, pass max as a tear-off to reduce (Lectures 035 and 044):

dart
import 'dart:math';

void main() {
  var marks = [72, 95, 64, 88];
  print(marks.reduce(max));
  print(marks.reduce(min));
}
output
95
64

A 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:

dart
import 'dart:math';

void main() {
  var random = Random();
  var dice = random.nextInt(6) + 1;
  print('Ali rolled $dice');
}
output
Ali rolled 2

Run 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:

dart
import 'dart:math';

void main() {
  var random = Random(42);
  print(random.nextInt(6) + 1);
  print(random.nextInt(6) + 1);
  print(random.nextInt(6) + 1);
}
output
2
1
1

7. Other Core Libraries

Several imports can sit together. Here are three more core libraries at work:

dart
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!');
}
output
{"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:

dart
// ali_tools.dart
String describe(int marks) => marks >= 50 ? 'Pass' : 'Fail';
dart
// 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:

dart
import 'ali_tools.dart';
import 'sara_tools.dart';

void main() {
  print(describe(72));
}
output
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:

dart
import 'ali_tools.dart';
import 'sara_tools.dart' as sara;

void main() {
  print(describe(72));
  print(sara.describe(72));
}
output
Pass
Marks: 72

Many programmers prefix dart:math too, so math.max reads clearly:

dart
import 'dart:math' as math;

void main() {
  print(math.max(72, 95));
  print(math.sqrt(81));
}
output
95
9.0

10. show and hide

show imports only the names you list. hide imports everything except them:

dart
import 'ali_tools.dart';
import 'sara_tools.dart' hide describe;

void main() {
  print(describe(72));
  print('sara'.shout());
}
output
Pass
SARA

hide 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:

dart
import 'dart:math' show sqrt, pi;

void main() {
  print(sqrt(25));
  print(pi);
}
output
5.0
3.141592653589793

Calling 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:

dart
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}));
}
output
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

dart
void main() {
  var name = 'Zayan';
  var age = int.parse('6');
  print('$name is $age');
  print(name.toUpperCase());
}
output
Zayan is 6
ZAYAN

Example 2 — Area of a Circle

dart
import 'dart:math';

void main() {
  var radius = 7;
  var area = pi * radius * radius;
  print('Area: ${area.toStringAsFixed(2)}');
}
output
Area: 153.94

Example 3 — max, min, pow

dart
import 'dart:math';

void main() {
  print(max(-3, 8));
  print(min(4.5, 2.5));
  print(pow(5, 3));
}
output
8
2.5
125

Example 4 — Seeded Dice

dart
import 'dart:math';

void main() {
  var random = Random(3);
  for (var i = 1; i <= 3; i++) {
    print('Roll $i: ${random.nextInt(6) + 1}');
  }
}
output
Roll 1: 2
Roll 2: 6
Roll 3: 5

Example 5 — An as Prefix

dart
import 'dart:math' as math;

void main() {
  var side = math.sqrt(49);
  print('Side: $side');
  print('Bigger: ${math.max(side, 6.5)}');
}
output
Side: 7.0
Bigger: 7.0

Example 6 — show Only What You Need

dart
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');
}
output
Hypotenuse: 10.0

Example 7 — Student Marks

dart
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}');
}
output
Best: 91
Worst: 55
Gap: 36

How it works

  1. math.max is passed to reduce as a tear-off — no parentheses.
  2. reduce keeps the bigger of each pair, ending with 91.
  3. The same works with math.min for the lowest mark.

Example 8 — Shopping Total as JSON

dart
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}));
}
output
{"items":3,"total":2050}

How it works

  1. dart:core gives the map and reduce; no import is needed for them.
  2. show jsonEncode imports a single function from dart:convert.
  3. jsonEncode writes keys in double quotes, as JSON requires.

Example 9 — Bank Balance with Interest

dart
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)}');
}
output
After 3 years: 1157.63

How it works

  1. Each year multiplies the balance by 1.05; three years is 1.05 to the power 3.
  2. math.pow(1.05, 3) is about 1.157625.
  3. toStringAsFixed(2) rounds to cents: 1157.63.

Example 10 — Last Three Temperatures

dart
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);
}
output
{31.0, 30.5, 32.0}

How it works

  1. Queue comes from dart:collection.
  2. Each new reading joins at the back with add.
  3. Once there are more than three, removeFirst drops the oldest, so only the latest three remain.

Common Beginner Mistakes

1. Forgetting the import

dart
void main() {
  // print(sqrt(16)); // ✗ without import 'dart:math'
}
output
Error: Method not found: 'sqrt'.

2. Putting import below other code

dart
void main() {
  print('x');
}

// import 'dart:math'; // ✗ must be at the top
output
Error: Directives must appear before any declarations.
Try moving the directive before any declarations.

3. Leaving out the quotes

dart
// import dart:math; // ✗
output
Error: Expected a String, but got 'dart'.

The library name is a string: import 'dart:math';.

4. Misspelling the library

dart
// import 'dart:maths'; // ✗
output
Error: Dart library 'dart:maths' is not available on this platform.

5. Adding a prefix, then forgetting it

dart
import 'dart:math' as math;

void main() {
  // print(sqrt(4)); // ✗
  print(math.sqrt(4));
}
output
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 analyze warns about unused imports.
  • Prefix libraries whose names are short or common, such as import 'dart:math' as math;.
  • Use show when you need one or two names from a big library.
  • Use hide to remove a single clashing name.
  • Seed Random while 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:

output
Rolls: 5 and 6
Total: 11
Higher: 6

Try it yourself before opening the solution.

Show solution
dart
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)}');
}
output
Rolls: 5 and 6
Total: 11
Higher: 6

How it works

  1. math.Random(7) always produces the same sequence, so the rolls are 5 and 6.
  2. math.max picks the higher of the two.

Practice Questions

Work through these in order — they run from beginner to application to challenge.

Beginner

  1. Import dart:math and print the square root of 144.
  2. Print pi rounded to two decimal places.
  3. Print the larger and the smaller of 15 and 40 using max and min.

Application

  1. Print the area of a circle with radius 10, rounded to two decimals.

  2. Import dart:math with the prefix math and print 3 to the power 4.

  3. Import only sqrt with show, and print the square root of 2.25.

  4. For the marks [48, 83, 97, 61], print the highest and lowest with reduce.

  5. This program does not compile. Fix it in two different ways:

    dart
    import 'dart:math' as math;
    
    void main() {
      print(sqrt(49));
    }

Challenge

  1. Sara saves 2000 at 10% interest per year for 2 years. Use pow to print Balance: 2420.00.
  2. Using Random(42), draw five lucky numbers from 1 to 100 into a list. Print the list and the biggest number.

Practice Answers

Question 1 — Solution

dart
import 'dart:math';

void main() {
  print(sqrt(144));
}
output
12.0

Question 2 — Solution

dart
import 'dart:math';

void main() {
  print(pi.toStringAsFixed(2));
}
output
3.14

Question 3 — Solution

dart
import 'dart:math';

void main() {
  print(max(15, 40));
  print(min(15, 40));
}
output
40
15

Question 4 — Solution

dart
import 'dart:math';

void main() {
  var area = pi * 10 * 10;
  print(area.toStringAsFixed(2));
}
output
314.16

Question 5 — Solution

dart
import 'dart:math' as math;

void main() {
  print(math.pow(3, 4));
}
output
81

Question 6 — Solution

dart
import 'dart:math' show sqrt;

void main() {
  print(sqrt(2.25));
}
output
1.5

Question 7 — Solution

dart
import 'dart:math';

void main() {
  var marks = [48, 83, 97, 61];
  print(marks.reduce(max));
  print(marks.reduce(min));
}
output
97
48

Question 8 — Solution

Either add the prefix to the call, or remove the prefix from the import:

dart
import 'dart:math' as math;

void main() {
  print(math.sqrt(49));
}
dart
import 'dart:math';

void main() {
  print(sqrt(49));
}

Both print:

output
7.0

Question 9 — Solution

dart
import 'dart:math';

void main() {
  var balance = 2000 * pow(1.10, 2);
  print('Balance: ${balance.toStringAsFixed(2)}');
}
output
Balance: 2420.00

Question 10 — Solution

dart
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)}');
}
output
[88, 59, 5, 86, 78]
Biggest: 88

The seed makes the draw repeatable; without it, every run gives new numbers.


Quick Revision

  1. What is a library in Dart?
  2. Which core library is imported automatically?
  3. Where must import lines go?
  4. Which library holds sqrt, pi and Random?
  5. How many numbers do max and min take?
  6. What does as do in an import?
  7. What is the difference between show and hide?
  8. Why would you give Random a seed?

Key Takeaways

  • Every Dart file is a library; privacy with _ is per library.
  • dart:core is imported automatically; other dart: libraries need import.
  • dart:math gives sqrt, pi, max, min, pow and Random.
  • Imports go at the top of the file, with the library name in quotes.
  • Two imports with the same name cause an error; an as prefix separates them.
  • show imports only the listed names; hide imports all but them — extensions included.
  • deferred as loads 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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.