How to use packages in dart

Packages are used in the Dart ecosystem to handle common software like libraries and tools. The pub package manager is used to obtain Dart packages. You can load packages from the local file system, remote locations, such as Git repositories, or via the website, which lists publicly accessible packages. Pub maintains version dependencies, enabling you to obtain package versions that are compatible with one another and with the SDK version, regardless of where your packages originate.

The majority of Dart-savvy IDEs include support for utilising pub, including package creation, download, updating, and publication. You can also use the command line programme dart pub.

A pubspec file is the bare minimum that constitutes a Dart package. Some package-related metadata can be found in the pubspec. Moreover, a package can

To use a package, do the following:

  • Create a pubspec (a file named pubspec.yaml that lists package dependencies and includes other metadata, such as a version number).
  • UseĀ dart pub getĀ to retrieve your packageā€™s dependencies.
  • If your Dart code depends on a library in the package, import the library.

Creating a pubspec

The top directory of your application contains a file with the name pubspec.yaml that contains the pubspec. The simplest pubspec possible merely includes the package name:

name: my_app

Here is an illustration of a pubspec that lists two packages (js and intl) that are hosted on the website as dependencies:

name: my_app

  js: ^0.6.0
  intl: ^0.17.0

Run the dart pub add command to update the pubspec.yaml file without manually modifying it. The sample that follows includes a reliance on vector_math.

 $ dart pub add vector_math
Resolving dependencies... 
+ vector_math 2.1.3
Downloading vector_math 2.1.3...
Changed 1 dependency!

Getting packages

Once you have a pubspec, you can run dart pub get from the top directory of your application:

 $cd <path-to-my_app>
 $dart pub get

Importing libraries from packages

To import libraries found in packages, use theĀ package:Ā prefix:

import 'package:js/js.dart' as js;
import 'package:intl/intl.dart';

Everything after package: is retrieved by the Dart runtime from your app’s package_config.json file.

This style can also be used to import libraries from your own package. Let’s assume that the transmogrify package looks like this:


HeĀ parser_test.dartĀ file can importĀ parser.dartĀ like this:

import 'package:transmogrify/parser.dart';

Upgrading a dependency

$ dart pub upgrade

TheĀ dart pub upgradeĀ command tells pub to regenerate the lockfile, using the newest available versions of your packageā€™s dependencies. If you want to upgrade only one dependency, you can specify the package to upgrade:

 $dart pub upgrade transmogrify
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x