'Flutter - Provider - provide services in main function without MultiProvider widget
In my app root widget I have multiple services provided using Provider library - MultiProvider widget.
I'm using flutter_native_splash with removeAfter functionality so I need some services to be initialized inside the main function and not inside the root App widget.
Meaning I need to find a way initialize the services and "provide" them without the MultiProvider widget and consume them later on down in the tree using the Consumer widget.
Any way to achieve this?
Solution 1:[1]
What do you mean by “injecting” services? There’s no dependency injection in Flutter. You can use the value constructor if you have existing ChangeNotifier instances. See Reusing an existing object instance
However, you shouldn’t really have business logic in view models, imo. You should have services that are independent, and use a library like GetIt to manage their instance lifetimes.
Solution 2:[2]
you can create a Signleton class and use it anywhere in app something like this,
Class Example{
Example._();
static final Example instance = Example._();
Future<void> init () async {
//initialise whatever you want
}
}
and use it in you main like this,
void main()async{
await Example.instance.init();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Riwen |
| Solution 2 |
