Real projects depend on packages from pub.dev and are split into libraries with clear public APIs.
Every Dart file is a library. import brings in another library's public names:
import 'dart:math';— core libraries.import 'package:http/http.dart' as http;— a package, with a prefix to avoid name clashes.import 'src/utils.dart';— a relative path within your package.showandhidelimit which names are imported:import 'dart:math' show max, pi;.
Privacy is per library: _names are private to the file. Big libraries can be split with part/part of, but most code just uses separate libraries. A package's public API lives in lib/, with implementation in lib/src/ and a top-level file that exports what users should see.
A package is a directory with a pubspec.yaml declaring its name, SDK constraint (environment: sdk: ^3.9.0), dependencies and dev_dependencies. Version constraints use caret syntax: http: ^1.2.0 means at least 1.2.0 but below 2.0.0.
Commands:
dart create my_app— new project.dart pub add http/dart pub add --dev test— add dependencies.dart pub get— resolve and download; writespubspec.lock(commit it for apps).dart pub outdatedanddart pub upgrade.dart run,dart analyze,dart format,dart fix --apply.
analysis_options.yaml configures the analyzer; package:lints provides recommended rules.
Example
# pubspec.yaml
name: weather_cli
description: A tiny command-line weather client.
version: 1.0.0
environment:
sdk: ^3.9.0
dependencies:
http: ^1.2.0
args: ^2.5.0
dev_dependencies:
lints: ^5.0.0
test: ^1.25.0
# lib/weather_cli.dart (the package's public API):
# export 'src/client.dart' show WeatherClient;
# bin/main.dart:
# import 'package:weather_cli/weather_cli.dart';
# import 'package:http/http.dart' as http;
# import 'dart:math' show max;
# Commands: dart pub get · dart run · dart analyze · dart testRemember
import ... as pandshow/hidecontrol names- Public API in
lib/, internals inlib/src/, re-exported withexport ^1.2.0allows compatible updates below 2.0.0
Watch out for
- Importing another package's
src/files directly — they're private implementation details.