14

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

BIS Tech
  • 17,000
  • 12
  • 99
  • 148

2 Answers2

19

There is an elegant way to do it, but we will have to create two separate class which extend changeNotifierProvider

class FirstNotifier with ChangeNotifier{
  double value=0; //default
  void ChangeValue(double newValue){
    value=newValue
    notifyListeners();
  }
}

And second notifier as ;

class SecondNotifier with ChangeNotifier{
  double value=0; //default
  void ChangeValue(double newValue){
    value=newValue
    notifyListeners();
  }
}

Then in inside your build method you can access them as

final firstNotifier = Provider.of<FirstNotifier>(context, listen:true)
final secondNotifier = Provider.of<SecondNotifier>(context, listen:true)

Then you can make changes in them as

firstNotifier.ChangeValue(30); 

In the MultiProvider Code, then you can wrap Providers as

return MultiProvider(
  providers: [
      ChangeNotifierProvider<FirstNotifier>(
        create: (_) => FirstNotifier,
      ),
      ChangeNotifierProvider<SecondNotifier >(
        create: (_) => SecondNotifier ,
      ),
  ],

That will do the trick

Saurabh Kumar
  • 2,088
  • 14
  • 17
13

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 mentioned in their official documentation: Can I obtain two different providers using the same type?

ynn
  • 3,386
  • 2
  • 19
  • 42
Viren V Varasadiya
  • 25,492
  • 9
  • 45
  • 61