DEV Community

Cover image for Some notes on Dart package encapsulation
nigel447
nigel447

Posted on

Some notes on Dart package encapsulation

This is a short note showing how I use dart package encapsulation to manage the dependency in a dart/flutter application.

If you are new to creating your own dart package there is a great post here on dev to help u get started How to Create Dart Packages in Flutter: A Step-by-Step Guide

Dependencies are always an issue and need to be managed carefully to avoid cycles among other things, Golang helps by throwing a compilation error if u have any Cyclic dependencies in your code. Creating acyclic dependency trees(graphs) preferably Directed DAG is what you want, you can research the details if u r interested.

Say you have a project with a few packages like below

Image description

Here I have a rest_client package among others, the rest_client package will use other dependency packages like Dio.

I want to use Dio response types in the main code.

To keep the dependency tree clean I dont want to import Dio types in the main source as well as the rest_client package, so I export Dio from the rest_client package as so

library rest_client;

export 'package:dio/dio.dart';
Enter fullscreen mode Exit fullscreen mode

In the main source code I import any needed Dio artifact from my rest_client package like

import 'package:rest_client/rest_client.dart' as transport;
class FreeAuthService  {

  final transport.Dio _dio = transport.Dio();
}
Enter fullscreen mode Exit fullscreen mode

now I am free to encapsulate all my related http transport code in the rest_client package and just return the Dio responses into the main source code.

Here are some minor details

  • packages are imported in pubspec like
  rest_client:
    path: packages/rest_client
Enter fullscreen mode Exit fullscreen mode
  • in the package directory source you need a top level file where you export the package dependencies you wish to expose like
library rest_client;

export 'package:dio/dio.dart';
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay