Summary: in this tutorial, you’ll learn about the Dart packages and how to import a package from pub.dev
into your package.
Introduction to the Dart packages
A package is a directory that contains a pubspec.yaml
file. The pubspec.yaml
stores the information of the package.
A package also may contain dependencies specified in the pubspec.yaml
file including libraries, resources, tests, images, etc.
Dart has two types of packages:
- Application packages
- Library packages
For example, when you create a Dart console program, the program itself is an application package.
Typically a package uses other packages. We say that the package depends on other packages that are called dependencies.
The pub.dev
website provides you with many packages for use with Dart and Flutter applications. The packages on pub.dev
are library packages.
Creating an application package
The following shows you how to create a full application (or application package) using Dart CLI tool.
First, launch a command prompt on Windows or a terminal on macOS and Linux.
Second, execute the following command to create a console application stored in the todos
directory:
dart create -t console todos
Code language: Dart (dart)
This command creates the application package and downloads the library packages from pub.dev. The output will be like the following:
Creating todos using template console...
.gitignore
analysis_options.yaml
CHANGELOG.md
pubspec.yaml
README.md
bin\todos.dart
lib\todos.dart
test\todos_test.dart
Running pub get...
Resolving dependencies...
Downloading test 1.21.2...
Downloading test_core 0.4.14...
Downloading test_api 0.4.10...
Downloading shelf_packages_handler 3.0.1...
Downloading pool 1.5.1...
Downloading term_glyph 1.2.1...
Downloading shelf_web_socket 1.0.2...
Downloading shelf_static 1.1.1...
Downloading package_config 2.1.0...
Downloading http_multi_server 3.2.1...
Downloading glob 2.1.0...
Downloading shelf 1.3.1...
Changed 46 dependencies!
Created project todos in D:\todos! In order to get started, run the following commands:
cd D:\todos
dart run
Code language: Dart (dart)
Third, navigate to the todos
directory:
cd todos
Code language: Dart (dart)
Finally, open the todos
in your favorite Dart editor. For example, you can open the todos
package in VS Code by running this command:
code .
Code language: Dart (dart)
The directory structure of the application will look like this:
├── bin/
| └── todos.dart
├── lib/
| └── todos.dart
├── test/
| └── todos_test.dart
├── analysis_options.yaml
├── CHANGELOG.md
├── pubspec.lock
├── pubspec.yaml
└── README.md
Code language: Dart (dart)
Here’s the contents of the pubspec.yaml
file:
name: todos
description: A sample command-line application.
version: 1.0.0
# homepage: https://www.example.com
environment:
sdk: '>=2.17.0 <3.0.0'
# dependencies:
# path: ^1.8.0
dev_dependencies:
lints: ^2.0.0
test: ^1.16.0
Code language: Dart (dart)
In the pubspec.yaml file:
name
: specifies the name of the application package.description
: a short description of the application.version
: is the version of the application. It follows the semantic versioning (major.minor.patch)environment
: specifies the Dart SDK version of the package.dependencies
list all library packages that the current package depends on. When a line starts with the #, it’s commented.dev_dependencies
are the dependencies that are relevant to the development environment only.
To execute the application, you run the following command from the command prompt or terminal inside the application package:
dart run
Code language: Dart (dart)
Dart will download all the dependencies, build the package and execute it. The output will look like the following:
Building package executable...
Built todos:todos.
Hello world: 42!
Code language: Dart (dart)
Adding a library package
First, add a library package from pub.dev to the current package by running the following command:
dart pub add <package_name>
Code language: Dart (dart)
For example, the following adds the http
package to the current package:
dart pub add http
Code language: Dart (dart)
It’ll output the following:
Resolving dependencies...
+ http 0.13.4
matcher 0.12.11 (0.12.12 available)
vm_service 8.3.0 (9.0.0 available)
Changed 1 dependency!
Code language: Dart (dart)
Also, it adds the http
package to the dependencies in the pubspec.yaml
file:
name: todos
description: A sample command-line application.
version: 1.0.0
environment:
sdk: '>=2.17.0 <3.0.0'
dependencies: {http: ^0.13.4}
dev_dependencies:
lints: ^2.0.0
test: ^1.16.0
Code language: Dart (dart)
The dependencies
section now has the http
library with a version.
Second, create posts.dart
file in the lib
folder of the package and place the following code:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
class Post {
final int userId;
final int id;
final String title;
final String body;
const Post({
required this.userId,
required this.id,
required this.title,
required this.body,
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
@override
String toString() {
return title;
}
}
Future<Post> fetchPost(int id) async {
final url = 'https://jsonplaceholder.typicode.com/posts/$id';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return Post.fromJson(jsonDecode(response.body));
} else {
throw HttpException('${response.statusCode}');
}
}
Code language: Dart (dart)
The following statement imports the http
library from the http
package:
import 'package:http/http.dart' as http;
Code language: Dart (dart)
The posts.dart
file contains the Post
class and fetchPost()
function:
- The
Post
class represents the post model. It has a factory constructor that returns aPost
object from JSON data. - The
fetchPost()
functions use http package to call an API provided jsonplaceholder.typicode.com to get a post by an id. Also, it uses thejsonDecode()
function andHttpException
fromdart:convert
anddart:io
libraries.
Third, use the following code in the bin/todos.dart
file:
import 'dart:io';
import 'package:todos/posts.dart';
void main() async {
try {
int id = 1;
var post = await fetchPost(id);
print('Post with $id: $post');
} on SocketException catch (e) {
print(e);
} on HttpException catch (e) {
print(e);
} on FormatException catch (e) {
print(e);
}
}
Code language: Dart (dart)
The todos.dart
file uses the dart:io
library:
import 'dart:io';
Code language: Dart (dart)
and posts.dart
library:
import 'package:todos/posts.dart';
Code language: Dart (dart)
Third, execute the following command to run the program:
dart run
Code language: Dart (dart)
It’ll output the following:
Building package executable...
Built todos:todos.
Post with 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Code language: Dart (dart)
Summary
- A Dart package is a directory that contains a
pubspec.yaml
file. It may also contain dependencies including other packages, images, etc.