Atiq Ur Rehman
Atiq Ur Rehman

Reputation: 1235

Flutter Better way to add Providers in main.dart file

In main.dart file I always have to add the same thing with different class name to make things works, here is an example.

MultiProvider(
          providers: [
            ChangeNotifierProvider<ProductDataProvider>(
                create: (_) => ProductDataProvider()),
            ChangeNotifierProvider<AuthenticationProvider>(
                create: (_) => AuthenticationProvider()),
          ],
          child: Container())

If we have 20 providers let's say then there is a lot duplicate code there right. Is any work around this?

Upvotes: 2

Views: 1926

Answers (1)

Alok
Alok

Reputation: 8978

See, if it is about initializing your provider in your main.dart, I am afraid, you have to do it, cos it need those. For any duplicates, you can make use of some short tricks and get going.

  1. Create an Array consisting of all your ChangeNotifiers, like in this case: ProductDataProvider and AuthenticationProvider
List<ChangeNotifier>_providersArray = [ProductDataProvider, AuthenticationProvider];
  1. Now, when you have the array, add it to the array which adds the ChangeNotifier, to your final providers list.
// This will be your array of Providers, which you will add to Mutliprovider(providers: HERE)
List<Provider> providers = []; // make sure you have the right type of the List<>, which the `providers` in `Multiproviders` accepts

for(var provider in _providersArray){
  //adding the provider name to the ChangeNotifier
  providers.add(ChangeNotifierProvider<provider>( create: (_) => provider()));
}
  1. Finally passing the providers in your Multiprovider
MultiProvider(
   providers: providers,
   child: Container()
)

Max to max, you will have to do the type casting for some type mismatches, and you're good to go. Let me know if that helps you in anyway.

Upvotes: 1

Related Questions