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
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';
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();
}
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
- 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';
Top comments (0)