Home > Back-end >  Flutter - Provider - inject services in main function without MultiProvider widget
Flutter - Provider - inject services in main function without MultiProvider widget

Time:02-15

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?

CodePudding user response:

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.

CodePudding user response:

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.init();
 }
  • Related