passing generic type by Function(T) in flutter
The way you are using the generic type T
is incomplete. The relationship between the StateFullConsumerWidget
and the _StateFullConsumerWidgetState
classes as written in your code are such that StateFullConsumerWidget
creates its state using the same T
type parameter as itself, so the widget knows the state uses the same generic type that it does. From the perspective of _StateFullConsumerWidgetState
, though, the class is declared as such:
class _StateFullConsumerWidgetState<T extends ChangeNotifier>
extends State<StateFullConsumerWidget>
The problem is the state class is using the general form of StateFullConsumerWidget
, so there is no explicit relationship between the T
that _StateFullConsumerWidgetState
is receiving as the type parameter and the T
that StateFullConsumerWidget
is using. Dart doesn't know how to reconcile this ambiguous relationship, so it defaults to the lowest common denominator the type constraints allow, which is ChangeNotifier
.
Because of this, when you try to treat T
as OnBoardingViewModel
, Dart throws an error because, as far as the state class knows, the T
of the parent widget is ChangeNotifier
, not OnBoardingViewModel
.
You can fix this by passing the type parameter along when you declare your state class:
class _StateFullConsumerWidgetState<T extends ChangeNotifier>
extends State<StateFullConsumerWidget<T>>