简体   繁体   English

Flutter 在 main.dart 文件中添加提供程序的更好方法

[英]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.在 main.dart 文件中,我总是必须使用不同的 class 名称添加相同的东西才能使事情正常工作,这是一个示例。

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.如果我们有 20 个提供者,假设那里有很多重复的代码。 Is any work around this?有什么解决方法吗?

See, if it is about initializing your provider in your main.dart , I am afraid, you have to do it, cos it need those.看,如果是关于在main.dart中初始化您的提供程序,恐怕您必须这样做,因为它需要这些。 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创建一个包含所有 ChangeNotifier 的数组,例如在本例中: ProductDataProviderAuthenticationProvider
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.现在,当您拥有该数组时,将其添加到将ChangeNotifier添加到您的最终providers列表的数组中。
// 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中传递提供程序
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 .最大到最大,您将不得不为某些类型不匹配进行类型转换,并且您对 go 很好 Let me know if that helps you in anyway.让我知道这是否对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM