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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools