Lesson 19 / 25

Libraries, Imports and pub.dev Packages

Organise code into libraries and use and publish packages.

Libraries and packages

Every Dart file is a library. Import other libraries with import 'package:shop/models/order.dart'; (from your own or another package's lib/ folder), import 'dart:convert'; for core libraries, or relative paths within the same package. Control names with as (prefixes, as in import 'package:http/http.dart' as http;), show and hide. Privacy is library-level: names starting with _ are visible only within their library. Conventionally, public API lives in lib/, implementation details in lib/src/, and a top-level lib/shop.dart exports the public parts. Packages come from pub.dev, which shows popularity, pub points (quality checks), platform support and verified publishers. Version constraints use caret syntax: ^1.2.0 allows >=1.2.0 <2.0.0. dart pub outdated shows available updates, dart pub upgrade updates within constraints, and dependency_overrides handles temporary conflicts. Publishing your own package requires a good README, CHANGELOG, licence, example and dart pub publish --dry-run first.

Libraries inside a package

Public API in lib/, implementation in lib/src/, and an export file exposing what users should see.

A folder tree with a top-level file glowing as the public entrance and a nested folder of greyed files behind it.
Figure 7.1 — Package layout with a public export file.

Imports, prefixes and an export file

Public API is exported; implementation stays in lib/src.

// lib/shop.dart (public entry point of package:shop)
library;

export 'src/models/order.dart' show Order, OrderStatus;
export 'src/services/checkout.dart' show Checkout;

// lib/src/services/checkout.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/order.dart';

class Checkout {
  Checkout(this._client);
  final http.Client _client;               // private to this library

  Future<Order> place(Order draft) async {
    final response = await _client.post(
      Uri.parse('https://api.example.com/orders'),
      headers: {'content-type': 'application/json'},
      body: jsonEncode(draft.toJson()),
    );
    return Order.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  }
}

// in an app:
// import 'package:shop/shop.dart';     // one import gives the public API

Check pub points and maintenance

Before adding a package, look at its pub.dev score, last release date, open issues and whether a verified publisher maintains it. Every dependency is code you will have to upgrade later.

Quick check: What does the version constraint ^1.2.0 allow in pubspec.yaml?

  • Any version from 1.2.0 up to but not including 2.0.0
  • Exactly 1.2.0
  • Any version at all
  • Only 1.2.x patch releases
Answer

Any version from 1.2.0 up to but not including 2.0.0 — Caret syntax allows compatible versions within the same major version.