Libraries
By Syncfusion®, Inc. · Last updated
How to import Dart's own libraries with prefixes, show and hide, split your code into your own libraries with private names, and add packages from pub.dev with pubspec.yaml and dart pub.
What Is a Library?
Library = a file (or group of files) of ready-made Dart code that other code can use.
For example:
- dart:math has square roots, pi and random numbers
- dart:convert turns data into JSON text and back
- your own file of school helper functions can be a library too
You import a library to use it, instead of writing that code yourself.
Simple lesson: a library is a toolbox of code. Import it, and its tools are ready to use.
A Real-World Example
Your school has a library of books.
- You do not write your own geometry textbook. You borrow one.
- Each book covers one subject, so you only carry what you need.
- Everyone in school uses the same book, so everyone learns the same rules.
Dart libraries are the same: shared, focused, and borrowed with one import line.
Every Run box on this page runs on the course's Dart runner in your browser.
It supports dart:core, dart:io, dart:math, dart:convert and dart:collection. Real Dart has more.
What You Will Learn
In this lesson, you will learn:
- What a library is, and how to import Dart's own libraries.
- How to use prefixes, show and hide.
- How to write your own libraries, and keep names private.
- What a package is, and what pubspec.yaml does.
- How to add, update and use packages with dart pub.
Library Fundamentals
Why Libraries Are Used
- Code reusability: write code once, use it in many programs.
- Less work: thousands of tested tools are already written for you.
- Order: each library holds one kind of tool, so big programs stay tidy.
- Fewer mistakes: library code is used by many people, so bugs are found fast.
Dart Core Libraries
Core library = a library that comes with Dart itself. Its name starts with dart:.
| Library | What it gives | Needs import? |
|---|---|---|
dart:core | print, int, String, List, Map, DateTime | No, always there |
dart:math | sqrt, pow, max, min, pi, Random | Yes |
dart:convert | jsonEncode, jsonDecode, utf8 | Yes |
dart:io | stdin, stdout, files (see File Handling) | Yes |
dart:async | Future, Stream (see Async Basics and Futures) | Yes |
dart:collection | Queue and other collections (see Sets) | Yes |
dart:core needs no import
void main() {
var marks = [78, 92, 65];
var today = DateTime(2026, 11, 14);
print(marks.length);
print(today.year);
print('Dart'.toUpperCase());
}
List, DateTime and String all come from dart:core. Dart imports it for you.
Simple lesson: dart:core is always there. Every other library needs an import line.
Importing Libraries
Import = a line at the top of a file that makes a library's names usable.
import 'dart:math';
- It goes at the very top of the file, before
main(). - It ends with
;.
Using dart:math
import 'dart:math';
void main() {
print(sqrt(2));
print(pow(2, 10));
print(max(84, 91));
print(pi);
var dice = Random();
var roll = dice.nextInt(6) + 1;
print(roll >= 1 && roll <= 6);
}
nextInt(6)gives 0 to 5, so+ 1makes it a dice roll from 1 to 6.- The last line prints
true, because the roll is always in range.
Remove the import line and run again. Dart says Method not found: 'sqrt'.
dart:convert
Turning data into JSON text
import 'dart:convert';
void main() {
var student = {'name': 'Asha', 'marks': [92, 85]};
var text = jsonEncode(student);
print(text);
var back = jsonDecode('{"name":"Ravi","age":13}');
print(back['name']);
}
You will use this a lot in File Handling.
Simple lesson: one import line at the top brings in a whole library of tools.
Library Prefixes
Prefix = a short name you give a library with as. You then write prefix.name.
Choose an import line and see which names you can use:
Why Prefixes Help
Two libraries, or your own code, may use the same name. A prefix tells Dart which one you mean.
Your max and dart:math's max, side by side
import 'dart:math' as math;
int max(List<int> marks) {
var best = marks[0];
for (var m in marks) {
if (m > best) best = m;
}
return best;
}
void main() {
print(max([78, 92, 65]));
print(math.max(78, 92));
print(math.pi.toStringAsFixed(2));
}
max(...)is your function, for a whole list.math.max(...)is the one from dart:math, for two numbers.
Simple lesson: as gives a library a prefix, so its names never clash with yours.
show and hide
show= import only these names.hide= import everything except these names.
show brings in only what you list
import 'dart:math' show max, pi;
void main() {
print(max(4, 9));
print(pi.toStringAsFixed(3));
}
A name that was not shown
import 'dart:math' show max;
void main() {
print(max(4, 9));
print(min(4, 9));
}
Dart says Method not found: 'min', because only max was shown.
When to use each import style
Simple lesson: show picks names in, and hide leaves names out.
Working with Your Own Libraries
Creating Libraries
Every .dart file is a library. Put helpers in their own file:
// lib/grades.dart
String gradeFor(int marks) {
if (marks >= 90) return 'A';
if (marks >= 75) return 'B';
if (marks >= 35) return 'C';
return 'Try again';
}
bool isPass(int marks) => marks >= 35;
Then import it from another file by its path:
// bin/report.dart
import '../lib/grades.dart';
void main() {
print(gradeFor(82));
print(isPass(30));
}
The output is B and then false.
- A path like
'../lib/grades.dart'= a file in your own project. - In a project made with
dart create, you usually write'package:my_app/grades.dart'instead (see packages, below).
Exporting Libraries
Export = make one library pass on another library's names.
// lib/school.dart
export 'grades.dart';
export 'attendance.dart';
Now import 'school.dart'; gives you everything from both files with one line.
In real Dart, a project has many files, and each one can import the others.
In this lab, each Run box is one file. The examples above are shown as plain code for that reason.
Simple lesson: every file is a library, import uses another file, and export passes names along.
Library Privacy
Private name = a name that starts with _. It can only be used inside its own library (its own file).
// lib/grades.dart
const _passMark = 35;
bool isPass(int marks) => marks >= _passMark;
- Another file can call
isPass(...). - Another file cannot use
_passMark. Dart says it is undefined there.
Inside one file, _ names work like any other name:
Private names inside one library
const _passMark = 35;
bool _isFail(int marks) => marks < _passMark;
void main() {
print(_isFail(20));
print(_isFail(60));
}
Dart has no private keyword. The _ at the start of the name is the rule. You will use it a lot in Encapsulation.
Easy way to remember
import= borrow a toolbox.as= put a label on the toolbox.show/hide= take only some tools, or leave some out._name= a tool that never leaves its own toolbox.
Simple lesson: a name that starts with _ is private to its file.
What Is a Package?
Package = a bundle of Dart libraries, written by someone else, that you can add to your project.
For example:
- http fetches data from the internet
- intl formats dates and numbers for different countries
- path joins and splits file paths safely
pub = Dart's package manager: the tool that downloads packages and keeps track of them.
pub.dev = the website where Dart and Flutter packages are shared.
Simple lesson: a package is a library from the community, and dart pub adds it to your project.
A Real-World Example
Your class makes a science project.
- You need a stopwatch. You borrow one from the lab instead of building it.
- The lab register notes who borrowed which stopwatch.
- Next year, a new class can borrow the same stopwatch.
Packages work like that. pubspec.yaml is the register, and pub.dev is the lab.
Packages are downloaded from the internet onto your computer by the dart pub command.
In this lab, the Run boxes cannot download packages. The commands are shown in an animated terminal, and the code that needs a package is shown as plain code.
Package Fundamentals
Why Packages Are Useful
- Save time: someone has already solved common problems, like reading dates.
- Tested code: popular packages are used by thousands of apps.
- Share your work: you can publish your own package for others.
- Stay small: you add only the packages your app needs.
The Package Ecosystem
Ecosystem = all the packages, their authors and the tools around them.
- Dart and Flutter share one ecosystem on pub.dev.
- Some packages are made by the Dart team (like
httpandpath). - Others are made by companies and volunteers.
Finding Packages on pub.dev
On a package's page, check these before you choose it:
- Likes and downloads = how many people use it.
- Pub points = a quality score out of 160.
- Verified publisher = the author's identity is checked, like
dart.dev. - Platforms = Android, iOS, web, desktop, or Dart only.
- Last updated = is it still looked after?
Simple lesson: choose packages that are popular, well scored and recently updated.
pubspec.yaml
pubspec.yaml = the file in your project's top folder that describes the project and lists its packages.
YAML = a simple text format that uses name: value lines and indentation.
name: school_app
description: A small app for Green Valley School.
version: 1.0.0
environment:
sdk: ^3.5.0
dependencies:
http: ^1.2.0
intl: ^0.19.0
dev_dependencies:
lints: ^4.0.0
test: ^1.25.0
Project Metadata
name= the package name, inlowercase_with_underscores.descriptionandversion= what it is, and which release.environment: sdk= which Dart versions can run it.
Dependencies and Dev Dependencies
dependencies= packages your app needs to run.dev_dependencies= packages you need only while building, like testing tools.
Package Versioning
Version number = major.minor.patch, like 1.2.3.
- patch (
1.2.3→1.2.4) = bug fixes only. - minor (
1.2.3→1.3.0) = new features, old code still works. - major (
1.2.3→2.0.0) = big changes, old code may break.
Caret syntax (^) = "this version or newer, but not the next major".
^1.2.0allows1.2.0up to (not including)2.0.0.^0.19.0allows0.19.0up to0.20.0, because0.xversions treat the minor number as major.
pubspec.lock = a file pub writes with the exact versions it chose. Everyone on the team gets the same ones.
YAML uses spaces to show what belongs to what. Tabs are not allowed.
Indent every package under dependencies: by exactly two spaces, or dart pub get stops with a parse error.
Simple lesson: pubspec.yaml lists what you want, and pubspec.lock records exactly what you got.
Managing Packages
Step through a real session. Watch pubspec.yaml change on the right:
Package Commands
| Command | What it does |
|---|---|
dart pub add http | adds the newest fitting version to dependencies, and downloads it |
dart pub add dev:test | adds it to dev_dependencies instead |
dart pub get | downloads everything listed in pubspec.yaml |
dart pub upgrade | moves to the newest versions your ranges allow |
dart pub remove http | removes the package from the project |
dart pub outdated | shows which packages have newer versions |
In a Flutter project, write flutter pub ... instead. It does the same jobs.
Simple lesson: add to start using a package, get to download, upgrade to update, and remove to stop.
Using Packages
Importing Package Libraries
A package import starts with package:, then the package name, then the file:
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
Without dart pub add first, Dart cannot find the package. Run this to see the error:
A package that was never added
import 'package:intl/intl.dart';
void main() {
print('Hello');
}
Dart says it Couldn't resolve the package 'intl'. The fix is dart pub add intl on your computer.
Using Third-Party Packages
Third-party package = a package not made by you and not part of Dart itself.
import 'package:intl/intl.dart';
void main() {
var exam = DateTime(2026, 11, 14);
var nice = DateFormat('EEEE, d MMM yyyy').format(exam);
print(nice);
}
On your computer, after dart pub add intl, this prints Saturday, 14 Nov 2026.
You can do simple formatting yourself with what you already know:
Formatting a date by hand, without a package
void main() {
var exam = DateTime(2026, 11, 14);
var d = exam.day.toString().padLeft(2, '0');
var m = exam.month.toString().padLeft(2, '0');
print('$d/$m/${exam.year}');
}
Simple lesson: import a package with package:name/file.dart, after adding it with dart pub add.
Popular Package Examples
Four packages you will meet often
Easy way to remember
- pub.dev = where packages live.
- pubspec.yaml = your shopping list.
- dart pub add = buy one. dart pub get = bring the whole list home.
- ^1.2.0 = "1.2.0 or newer, but not 2.0".
Simple lesson: check dart: libraries first, and add a package when it saves real work.
TL;DR
- Every Dart file is a library.
import 'dart:math';brings in Dart's own. as madds a prefix.showpicks names.hideleaves names out.- Your own files:
import 'helpers.dart';. A_nameis private to its file. - A package is a bundle of libraries from pub.dev, listed in
pubspec.yaml. dart pub add name,dart pub get, thenimport 'package:name/name.dart';.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Using sqrt with no import | Math is built in | It lives in dart:math | Method not found: 'sqrt'. |
import below main() | Imports can go anywhere | Imports go at the very top | A syntax error. |
| Forgetting the prefix | as math still allows max | Write math.max | Method not found: 'max'. |
| Using a name that was not shown | show limits nothing | Only shown names are imported | Method not found. |
Using _secret from another file | _ is only a style | _ makes it private to its file | Undefined name. |
Importing dart:core | It is needed | It is always there | Nothing breaks, but it is extra noise. |
| Importing before adding | An import downloads it | Run dart pub add first | Couldn't resolve the package. |
| Editing pubspec.yaml, then not running get | It updates by itself | Run dart pub get after editing | The new package is missing. |
| Wrong indentation in YAML | Spaces do not matter | YAML uses spaces to group lines | A pubspec parse error. |
A test tool under dependencies | All packages are the same | Build-only tools go in dev_dependencies | A bigger app than needed. |
| Deleting pubspec.lock to "fix" things | It is a cache | It keeps the team on the same versions | Different versions on each computer. |
| Choosing any package | All packages are equal | Check likes, points, publisher and updates | Bugs and abandoned code. |
Check Yourself
Exercises
What to Remember
- A library is a file of code you can import.
- Use prefixes,
showandhideto avoid name clashes. - A name starting with
_stays inside its file. - Packages come from pub.dev and are listed in pubspec.yaml.
- Use
dart pub addto add a package, then import it withpackage:.
Next: Classes. You will learn to design your own types, like a Student with a name, marks and methods.