depend
is a library for dependency management in Flutter applications. It provides a convenient way to initialize and access services and repositories via InheritedWidget
.
- Dependency Initialization: Prepare all dependencies before the app launches.
- Global Access: Access dependencies from anywhere in the widget tree.
- Parent Dependencies Support: Easily create nested or connected dependencies.
- Ease of Use: Integrate the library into existing code with minimal changes.
Add the library to the pubspec.yaml
of your project:
dependencies:
depend: ^latest_version
Install the dependencies:
flutter pub get
Create a class that extends DependencyContainer
and initialize your dependencies:
class RootContainer extends DependencyContainer {
final ApiService apiService;
RootContainer({required this.apiService});
void dispose() {
apiService.dispose();
}
}
Create a class that extends DependencyContainer
and initialize your dependencies:
class RootDependencyFactory extends DependencyFactory<RootContainer> {
Future<RootContainer> create() async {
return RootContainer(
apiService: await ApiService.initialize(),
);
}
// or
RootContainer create() {
return RootContainer(
apiService: ApiService.initialize(),
);
}
}
Wrap your app in a DependencyScope
to provide dependencies:
void main() {
runApp(
DependencyScope<RootContainer, RootFactory>(
factory: RootFactory(),
placeholder: const Center(child: CircularProgressIndicator()),
builder: (BuildContext context) => const MyApp(),
),
);
}
You can now access the dependency using DependencyProvider
anywhere in the widget tree:
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final apiService = DependencyProvider.of<RootContainer>(context).apiService;
return FutureBuilder(
future: apiService.getData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Data: ${snapshot.data}');
},
);
}
}
final RootContainer dep = await RootFactory().create();
DependencyProvider<RootContainer>(
dependency: dep,
builder: () => YourWidget();
// or
child: YourWidget()
)
class YourWidget extends StatelessWidget {
@override
Widget build(BuildContext) {
root = DependencyProvider.of<RootContainer>(context);
...
}
}
DependencyScope<RootContainer, RootFactory>(
factory: RootFactory(),
builder: (BuildContext context) => Text('Inject'),
placeholder: Text('Placeholder'),
errorBuilder: (Object? error) => Text('Error'),
),