how to add multiple ChangeNotifierProvider in same type in Flutter

左心房为你撑大大i 提交于 2021-02-08 19:42:05

问题


Is it possible to add same type multiple ChangeNotifierProvider?

return MultiProvider(
  providers: [
      ChangeNotifierProvider<ValueNotifier<double>>(
        create: (_) => ValueNotifier<double>(0.0),
      ),
      ChangeNotifierProvider<ValueNotifier<double>>(
        create: (_) => ValueNotifier<double>(0.0),
      ),
  ],

In my build method

 @override
  Widget build(BuildContext context) {
    ValueNotifier<double> firstNotifier = Provider.of(context, listen: true);
    ValueNotifier<double> secondNotifier = Provider.of(context, listen: true);

  print('First value ${firstNotifier.value} Second value ${secondNotifier.value}');

 ...
 onTap:(){
   firstNotifier.value = 10.0;
   secondNotifier.value = 30.0;
 }

both printed values are same First value is 10 Second value is 10


回答1:


It is impossible to do so. You have to provide different types of provider to get correct value.

If you use same provider more than once then it will give you value of nearest provider value in widget tree.

It is also mention in their official documentation.

check out here. Can I obtain two different providers using the same type?



来源:https://stackoverflow.com/questions/61052629/how-to-add-multiple-changenotifierprovider-in-same-type-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!