Sub topic 7
Importing a Package and Calling Its API
This chapter assumes you can already add a package with flutter pub add and that pubspec.lock exists in your project. It covers what an import line means, how to control which names it brings in, and how to learn a new API quickly. It also covers the errors you will most likely hit on the first call.
What an import resolves to
Adding a package to pubspec.yaml only makes it available. Your Dart code can't use it until you import a library from it. A package: import has two parts: the package name and a path inside that package's lib/ directory.
import 'package:http/http.dart' as http;This line means: in the package named http, open lib/http.dart. Dart finds where that package lives by reading .dart_tool/package_config.json, a file that flutter pub get generates. It maps each package name to a directory, usually in the pub cache on your machine.
Two consequences follow:
- If
pub gethas not run since you editedpubspec.yaml, the mapping is missing and the import fails. - Only files under
lib/can be imported this way. Everything else in a package (tests, tools,example/) is not part of its public surface.
Import forms you will use
| Form | Example | Effect |
|---|---|---|
| Plain | `import 'package:http/http.dart';` | All public names go into your file's scope |
| Prefixed | `import 'package:http/http.dart' as http;` | Names are reached as `http.get`, `http.Client` |
| Show | `import 'package:http/http.dart' show Client;` | Only `Client` is imported |
| Hide | `import 'package:http/http.dart' hide Client;` | Everything except `Client` is imported |
| Relative | `import 'models/user.dart';` | A file in your own package |
Use a prefix for packages with short, generic names like get, post, or Client. The http package is the standard example. Without the prefix, get(...) would be unclear when you read the code later.
Use show or hide when two libraries export the same name and you can't prefix one of them. For example, if two packages both define Response:
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart' show Dio;
void main() {
final Dio dio = Dio();
final http.Client client = http.Client();
print('${dio.runtimeType} ${client.runtimeType}');
client.close();
}This sketch assumes you also added dio. It compiles because Dio is the only name taken from that package, and http.Client stays under its prefix.
A first call, step by step
The spine example is a good starting point. Here is the same function with the reasoning spelled out:
import 'package:http/http.dart' as http;
Future<String> fetchBody() async {
final response = await http.get(Uri.parse('https://example.com'));
if (response.statusCode == 200) {
return response.body;
}
throw Exception('Request failed: ${response.statusCode}');
}Uri.parseturns a string into aUri. Thehttppackage takes aUri, not aString, since version 0.13.http.getreturns aFuture<http.Response>, so youawaitit inside anasyncfunction.- The package does not throw on a 404 or 500 status. It returns a
Response, and checkingstatusCodeis your job.
This convenience function opens and closes a connection for each call. For several requests to the same host, create one Client, reuse it, and close it when you finish:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Map<String, dynamic>> fetchTodo(int id) async {
final client = http.Client();
try {
final uri = Uri.https('jsonplaceholder.typicode.com', '/todos/$id');
final response = await client.get(uri);
if (response.statusCode != 200) {
throw http.ClientException('Unexpected status ${response.statusCode}', uri);
}
return jsonDecode(response.body) as Map<String, dynamic>;
} finally {
client.close();
}
}
Future<void> main() async {
final todo = await fetchTodo(1);
print(todo['title']);
}Here dart:convert comes from the Dart SDK, so it needs no entry in pubspec.yaml. Uri.https builds the URL from parts and handles escaping, which is safer than concatenating strings. The finally block closes the client even when the request throws.
Using the result in a widget
In Flutter, the usual pattern is to start the future once and let FutureBuilder render each state. Create the future in initState, not in build, or the request restarts on every rebuild.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(const MaterialApp(home: BodyPage()));
class BodyPage extends StatefulWidget {
const BodyPage({super.key});
@override
State<BodyPage> createState() => _BodyPageState();
}
class _BodyPageState extends State<BodyPage> {
late final Future<String> _body;
@override
void initState() {
super.initState();
_body = _load();
}
Future<String> _load() async {
final response = await http.get(Uri.parse('https://example.com'));
if (response.statusCode == 200) return response.body;
throw Exception('Request failed: ${response.statusCode}');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<String>(
future: _body,
builder: (context, snapshot) {
if (snapshot.hasError) return Center(child: Text('${snapshot.error}'));
if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
return SingleChildScrollView(child: Text(snapshot.data!));
},
),
);
}
}Learning an unfamiliar API
You rarely need to read a package's source. Work through these pages on pub.dev in order:
- Readme tab. Look for a quick-start snippet and any setup steps.
- Example tab. This shows the contents of the package's
example/directory, which is usually the most reliable code to copy. - API reference. Open the "API docs" link to see every public class, method, and parameter with its types.
- Changelog tab. Check it when a snippet from a blog post doesn't compile. The API may have changed between major versions.
In your editor, hovering over a name shows its documentation, and "Go to definition" opens the package source. The analyzer autocompletes members based on the declared types, so you can often discover methods by typing the variable name followed by a dot.
Common errors and how to fix them
| Message or symptom | Likely cause | Fix |
|---|---|---|
| `Target of URI doesn't exist: 'package:http/http.dart'` | Package not in `pubspec.yaml`, or `pub get` has not run | Run `flutter pub add http`, then restart the analysis server if the error stays |
| `The function 'get' isn't defined` | Import has a prefix, call has none | Write `http.get(...)` |
| `The argument type 'String' can't be assigned to 'Uri'` | Passing a string URL | Wrap it with `Uri.parse(...)` |
| Lint `depend_on_referenced_packages` | You import a package that only arrives transitively | Add it to your own `pubspec.yaml` |
| `Undefined name` after copying a snippet | Snippet is for a different major version | Check the changelog and your constraint |
| `Don't import implementation files` style warning | Import path contains `src/` | Import the public library instead |
The transitive case matters. If package A depends on package B, B is installed, and your code may even compile when it imports B. But A can drop B in any release, and your build then breaks without any change on your side. Add every package you import directly to your own pubspec.yaml.
Importing your own code
Inside your app, either style works, but pick one and stay consistent. The Dart style guide prefers relative imports for files within the same package's lib/, because they are shorter and don't break if you rename the package. Code outside lib/, such as files in test/, should use package:your_app/... to reach into lib/.
// In lib/screens/home.dart, importing a sibling folder:
import '../models/user.dart';
// In test/user_test.dart, importing from lib/:
import 'package:my_app/models/user.dart';Don't mix both styles for the same file. Doing so can create two distinct library identities in some cases, and you may see type mismatches between classes that look identical.
Exercise
You add intl with flutter pub add intl and write DateFormat('yMd').format(DateTime.now()) in lib/main.dart. The analyzer reports Undefined class 'DateFormat'. What is missing, and what would you write to import only that class?
Show answer
The file has no import. Add import 'package:intl/intl.dart' show DateFormat; at the top. The show clause limits the import to DateFormat, and the package being in pubspec.yaml is not enough on its own.
Exercise
Your app imports package:path/path.dart and works, but you never added path to pubspec.yaml. It arrives because another dependency uses it. Why is this risky, and how do you fix it?
Show answer
The other package can remove or change its path dependency in any release, which would break your build without any change in your code. The depend_on_referenced_packages lint flags this. Fix it by running flutter pub add path so your own pubspec.yaml declares it.