I am working on a Flutter app where I need to dynamically determine which ChangeNotifierProvider
to use based on a specific condition (an enum type). Here is the code I have:
return ChangeNotifierProvider(
create: (context) {
switch (widget.type) {
case MasterDataType.block:
return di.locator<BlockProvider>();
case MasterDataType.employee:
return di.locator<EmployeeProvider>();
default:
return di.locator<VehicleProvider>();
}
},
builder: (context, _) {
return Scaffold(
appBar: AppBar(title: const Text("List of <SelectedProvider>")),
body: const Center(
child: Text("Data from ${context.watch<SelectedProvider>().data}"),
),
);
},
);
However, when I run this code, the ChangeNotifierProvider
does not infer the correct generic type (ChangeNotifierProvider<BlockProvider>
, ChangeNotifierProvider<EmployeeProvider>
, or ChangeNotifierProvider<VehicleProvider>
). Instead, it defaults to ChangeNotifierProvider<ChangeNotifier>
.
My questions are:
-
How can I make the ChangeNotifierProvider dynamically select the correct provider and infer the proper type?
-
Is there a better approach for dynamically selecting the provider based on
widget.type
?
Here is some additional context about my setup:
-
I am using GetIt for dependency injection.
-
MasterDataType is an enum with the following values:
enum MasterDataType { block, employee, vehicle }
-
Each provider (BlockProvider, EmployeeProvider, VehicleProvider) extends ChangeNotifier.
Thank you for your guidance!
I tried dynamically selecting the ChangeNotifierProvider by using a switch statement in the create method, as shown in the code above. I expected the provider to infer the correct generic type (ChangeNotifierProvider<BlockProvider>, ChangeNotifierProvider<EmployeeProvider>, or ChangeNotifierProvider<VehicleProvider>) based on the widget.type.
However, instead of inferring the specific provider type, the ChangeNotifierProvider defaults to ChangeNotifierProvider<ChangeNotifier>, which causes issues when I try to use context.watch<BlockProvider>() or other specific types later in the widget tree.
Naufan Irfanda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.