问题
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