Sub topic 2
Adding Packages from pub.dev to a Flutter Project: Reading Version Constraints
This chapter assumes you know basic Dart syntax, have a project made with flutter create, can run commands in a terminal, and can read YAML.
Reading version constraints
A version constraint tells the pub tool which versions of a package your app accepts. You write constraints in the dependencies section of pubspec.yaml.
dependencies:
flutter:
sdk: flutter
http: ^1.2.0The caret ^1.2.0 means "1.2.0 or newer, but below 2.0.0." A major version change may break the API, so the caret accepts only compatible updates. For packages at 0.x, the caret is stricter. ^0.2.0 allows >=0.2.0 <0.3.0.
pub get and pubspec.lock
Running flutter pub get resolves each constraint to one concrete version per package. It writes the results to pubspec.lock.
flutter pub getCommit pubspec.lock for apps so every machine uses the same versions. Do not edit it by hand. To move to newer versions that still fit your constraints, run flutter pub upgrade.
Importing a package and calling its API
After a package resolves, import it with a package: URI. The as prefix keeps its names from clashing with yours.
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}');
}http.get returns a Future<Response>, so you call it with await. Check the status code before you read the body.
Exercise
Your pubspec.yaml contains http: ^1.2.0. Which of these versions can pub get select: 1.9.0, 2.0.0, or 0.9.0?
Show answer
1.9.0. The caret allows any version at or above 1.2.0 and below 2.0.0, so 2.0.0 and 0.9.0 fall outside the range.