Hi Devs! I write this article to help you to manage dependencies in Flutter using my package Flutter Injection.
When you create a Flutter App maybe you search for a problem " How do I get this information in my other classes?" such as a User session to get a name on the Profile Page. So, I helps you to solve that!
The first step to understanding how that package can help you, I need to present the problem.
The problem
You need to create a Flutter Application with Login and HomePage when HomePage needs to appear the information logged user.
From this example, the user information is below.
{
"name": "Gabul",
"profileUrl": "https://google.com",
"id": "user-ID",
"email": "user@email.com",
}
Normally you think of using a singleton implementation or using InheritedWidget to provide this information to your children. That is a good solution but is not easier to use.
So, to solve it I created a new solution to help you manage all dependencies in your project using the easy way to implement that.
My package named Flutter Injections helps you. Let's go through the code and learn how this works.
The Code
I published this package on pub.dev and you see more information here.
First Step
You can put the package on your pubspec.yaml file.
flutter_injections: ^any # or current version
Second Step
The principle of this package is "simple to use". So, you need to import packages into files when you need to add dependencies.
import 'package:flutter_injections/flutter_injections.dart';
Third Step
Now you get the Flutter Injections widget when that file is the parent of the children when you need to use your dependencies. See the example below.
class YourPageInjections extends StatelessWidget {
const YourPageInjections({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return FlutterInjections(injections: [
Inject<YourRepository>((i) => YourRepository(client: i.find<Dio>())),
Inject<YourController>(
(i) => YourController(repository: i.find<YourRepository>())),
], child: const YourPage());
}
}
That's it. Now you can get all dependencies in your child using the simple code below.
final controller = FlutterInjections.get<YourController>();
If you need to dispose of the dependencies is simple too.
FlutterInjections.dispose<YourController>();
I created the complete example to help you to understand more ways of using this.
I will create new examples and post new articles.