BIS Tech
BIS Tech

Reputation: 19514

how to add multiple ChangeNotifierProvider in same type in Flutter

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

Upvotes: 18

Views: 33158

Answers (2)

Saurabh Kumar
Saurabh Kumar

Reputation: 2803

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

Upvotes: 21

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27197

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?

Upvotes: 15

Related Questions