Reputation: 1235
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
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.
- Create an Array consisting of all your ChangeNotifiers, like in this case:
ProductDataProvider
andAuthenticationProvider
List<ChangeNotifier>_providersArray = [ProductDataProvider, AuthenticationProvider];
- Now, when you have the array, add it to the array which adds the
ChangeNotifier
, to your finalproviders
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()));
}
- 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