Flutter (12): Package Management

Time: Column:Mobile & Frontend views:186

12.1 Introduction

In software development, there are often libraries or SDKs that many projects may need to use. To improve development efficiency, these common codes can be extracted into an independent module. Then, any project that needs them can directly integrate the module. Many programming languages or development tools support this "module sharing" mechanism. For example, in Java, such modules are packaged into JAR files, in Android as AAR files, and in web development, NPM packages are used. For clarity, we refer to these shareable independent modules as "Packages."

In real-world app development, an app often depends on many packages, which usually have interdependencies or version constraints. Managing these packages manually can be cumbersome. Therefore, most development ecosystems or programming languages offer package management tools. For example, Android provides Gradle for managing dependencies, iOS uses Cocoapods or Carthage, and Node uses NPM. Flutter has its own package management tool as well. In this section, we will mainly introduce how to manage third-party dependency packages in Flutter using the configuration file pubspec.yaml, located in the root directory of the project.

YAML is a human-readable data format with high readability and is often used in configuration files. Compared to XML or JSON, YAML has a simpler syntax and is easier to parse. In Flutter, the default configuration file is pubspec.yaml. Here's a simple example:

name: flutter_in_actiondescription: First Flutter Application.version: 1.0.0+1dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2dev_dependencies:
  flutter_test:
    sdk: flutter
    flutter:
  uses-material-design: true

Now, let's explain each field:

  • name: The name of the application or package.

  • description: A description or introduction of the application or package.

  • version: The version number of the application or package.

  • dependencies: Other packages or plugins that the application or package depends on.

  • dev_dependencies: Tools required during development (not dependencies for the Flutter application itself).

  • flutter: Flutter-related configuration options.

If our Flutter application depends on a package, we need to add it under the dependencies section. Next, we'll demonstrate how to add, download, and use a third-party package with an example.


12.2 Pub Repository

Pub is Google's official Dart Packages repository, similar to NPM in Node.js or JCenter in Android. You can search for packages and plugins on Pub, and you can also publish your own packages and plugins there. In later sections, we will introduce how to publish packages to Pub.


12.3 Example

Let's implement a widget that displays a random string. There is an open-source package called "english_words" that contains thousands of commonly used English words and other useful functions. First, find the english_words package on Pub (as shown in Figure) and check its latest version and Flutter support.

Flutter (12): Package Management

We see that the latest version of english_words is 4.0.0 and it supports Flutter. Now:

  1. Add english_words to the dependencies list:

dependencies:
  flutter:
    sdk: flutter
  # Newly added dependency
  english_words: ^4.0.0
  1. Download the package. In Android Studio, when viewing pubspec.yaml (Figure), click Pub get in the top-right corner.

Flutter (12): Package Management

This will install the dependencies in your project. You will see the following in the console:

flutter packages getRunning "flutter packages get" in flutter_in_action...
Process finished with exit code 0

You can also navigate to your project directory in the terminal and manually run the command flutter packages get to download dependencies.

  1. Import the english_words package:

import 'package:english_words/english_words.dart';

When typing, Android Studio will provide suggestions for importing libraries. After importing, the code line will appear gray, indicating that the library has not yet been used.

  1. Use the english_words package to generate a random string:

class RandomWordsWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Generate random string
    final wordPair = WordPair.random();
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Text(wordPair.toString()),
    );
  }
}
  1. Add RandomWordsWidget to the Column in _MyHomePageState.build:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    ... // Other widgets
    RandomWordsWidget(),
  ],
)

If the application is running, use the hot reload button (⚡️) to update the running application. Each time you click hot reload or save the project, a different word pair will be generated and displayed in the running app. This is because the word pair is generated inside the build method, which runs each time the app reloads. The effect is shown in Figure.

Flutter (12): Package Management


12.4 Other Dependency Methods

The dependency method described above relies on the Pub repository. However, you can also depend on local packages or Git repositories.

  1. Local Package Dependencies
    If you're developing a package locally, named pkg1, you can depend on it as follows:

dependencies:
  pkg1:
    path: ../../code/pkg1

The path can be either relative or absolute.

  1. Git Dependencies
    You can also depend on a package stored in a Git repository. If the package is located at the root of the repository, use the following syntax:

dependencies:
  pkg1:
    git:
      url: git://github.com/xxx/pkg1.git

If the package is not in the root directory, use the path parameter to specify its relative location:

dependencies:
  package1:
    git:
      url: git://github.com/flutter/packages.git
      path: packages/package1

These are common dependency methods in Flutter development, but there are others as well. For a complete list, visit: https://www.dartlang.org/tools/pub/dependencies.


12.5 Summary

This section introduced the overall process of managing, referencing, and downloading packages in Flutter. In later chapters, we will cover how to develop and publish your own packages.