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
This class is basically a provider-wrapper over a class that implements ChangeNotifier. According to the Flutter docs, a ChangeNotifier is 'a class that can be extended or mixed in that provides a change notification API using VoidCallback for notifications.' In practical terms, other objects can listen to a ChangeNotifier object.
A ChangeNotifierProvider is as valid as a Provider. Provider itself is just a more general use case. They are all valid providers. I can change the example for you. Probably, you can alter the answers. The recommended one you could show first and then another alternative.
The provider is a way to handle State management in flutter applications. Like the Inherited widget, we can handle the data changes with providers. CartPage : Which contains all cart items with Remove option.
If you want to pass variables to your ChangeNotifier, consider using ChangeNotifierProxyProvider. If you already have an instance of ChangeNotifier and want to expose it, you should use ChangeNotifierProvider.value instead of the default constructor. Failing to do so may dispose the ChangeNotifier when it is still in use.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With