Packages & Imports in Dart
In this lesson, you will learn how packages and imports work in Dart. Packages allow you to reuse existing code, organize large projects, and build scalable applications efficiently.
Almost every real-world Dart application uses external packages — especially for HTTP requests, file handling, JSON parsing, and testing.
What Is a Package?
A package in Dart is a collection of reusable code such as:
- Libraries
- Utilities
- Tools and helpers
Packages help developers avoid rewriting common functionality.
The pub.dev Package Repository
Dart uses pub.dev as its official package repository.
It contains thousands of community-maintained and official packages for:
- Networking
- Data processing
- CLI tools
- Testing
- Flutter & backend development
Adding a Package Using pubspec.yaml
All Dart packages are managed using the pubspec.yaml file.
Example: Adding the http package.
dependencies:
http: ^1.2.0
After adding a dependency, run:
dart pub get
Importing a Package
Once installed, you can import a package using the import keyword.
import 'package:http/http.dart' as http;
The as keyword helps avoid naming conflicts.
Real-World Example: HTTP Request
Let’s fetch data from an API using the http package.
import 'package:http/http.dart' as http;
void main() async {
var response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts/1')
);
print(response.body);
}
This code performs a real HTTP GET request and prints the response.
Importing Dart Core Libraries
Dart provides built-in libraries that can be imported easily.
import 'dart:io';
import 'dart:math';
import 'dart:convert';
These libraries are part of Dart itself and do not require installation.
Importing Your Own Files
You can import files from your own project to keep code organized.
Project structure:
lib/
├── utils.dart
└── main.dart
Importing utils.dart into main.dart:
import 'utils.dart';
Using show and hide
You can control which members are imported using show and hide.
import 'dart:math' show pi, sqrt;
import 'dart:math' hide Random;
This improves readability and avoids unnecessary imports.
Prefixing Imports
Prefixes help avoid conflicts when different libraries have similar names.
import 'dart:math' as math;
void main() {
print(math.pi);
}
Best Practices for Packages & Imports
- Use trusted and actively maintained packages
- Keep dependencies minimal
- Use prefixes for clarity
- Remove unused packages
📝 Practice Exercises
Exercise 1
Add a package to pubspec.yaml and install it.
Exercise 2
Import the dart:math library and print the value of pi.
Exercise 3
Create two Dart files and import one into the other.
✅ Practice Answers
Answer 1
dependencies:
http: ^1.2.0
Answer 2
import 'dart:math';
void main() {
print(pi);
}
Answer 3
// main.dart
import 'utils.dart';
// utils.dart
int add(int a, int b) => a + b;
What’s Next?
In the next lesson, you will learn about Dart CLI Basics, where you’ll build and run Dart programs directly from the command line.