I'm trying to pass a dynamic type argument to the Provider.of<T>(context)
class CustomInputField extends StatelessWidget {
final Type stateClass;
CustomInputField({
Key key,
this.stateClass,
}) : super(key: key);
@override
Widget build(BuildContext context) {
var state = Provider.of<stateClass>(context);
return TextFormField(
key: state.key,
...
);
}
}
But this gives me following error:
The name 'stateClass' isn't a type so it can't be used as a type argument. Try correcting the name to an existing type, or defining a type named 'stateClass'.
Anyone knows how to correctly do this?
It could be that this is not a good practice, or maybe it's even impossible. But thing is, I would like to make a single CustomInputField
widget for all the inputfields in my app. I'm using the ChangeNotifierProvider
class from the Provider package and would like to pass different states to this CustomInputField
widget
You can't pass a type to generic dynamically in Dart. The only way to do it is to have switch/if-else block and return objects with different type in generic.