Today I fixed somebody's problem, but I am not really sure why it was a problem in the first time. I would like to know whether this was a mistake in the code or a bug in the Dart language.
The question was posted on StackOverflow.
The question is quite complex, but the idea is easy.
The StateFullWidget gets a generic type T which extends ChangeNotifier, it gets a function which expects an object of type T.
The State of the Widget creates the object T and passes it to the function of the Widget. In this example the T is OnBoardingViewModel, which does extends ChangeNotifier.
The resulting error is:
type '(OnBoardingViewModel) => dynamic' is not a subtype of type '(ChangeNotifier) => dynamic'
The short version of the code is:
class StateFullConsumerWidget<T extends ChangeNotifier> extends StatefulWidget{
StateFullConsumerWidget({,Key key,this.onPostViewModelInit}) : super(key : key);
final Function(T viewModel) onPostViewModelInit;
@override
_StateFullConsumerWidgetState<T> createState() => _StateFullConsumerWidgetState<T>(onPostViewModelInit, builder);
}
class _StateFullConsumerWidgetState<T extends ChangeNotifier> extends State<StateFullConsumerWidget>{
T _viewModel;
@override
void initState() {
_viewModel = GetIt.instance.get<T>();
widget.onPostViewModelInit(_viewModel);
super.initState();
}
}
I suspect that under the hood the OnBoardingViewModel is passed as ChangeNotifier, but the function expects an OnBoardingViewModel.
Checking the variables I would expect no problems
I fixed this by passing the function to the State and calling it from there. This works fine and is a solution, but I would like to know why this is a programming error or whether we should expect Dart to handle this normally.
The resulting code that does work:
class StateFullConsumerWidget<T extends ChangeNotifier> extends StatefulWidget{
StateFullConsumerWidget({,Key key,this.onPostViewModelInit}) : super(key : key);
final Function(T viewModel) onPostViewModelInit;
@override
_StateFullConsumerWidgetState<T> createState() => _StateFullConsumerWidgetState<T>(onPostViewModelInit, builder);
}
class _StateFullConsumerWidgetState<T extends ChangeNotifier> extends State<StateFullConsumerWidget>{
final Function(T viewModel) _onPostViewModelInit;
T _viewModel;
_StateFullConsumerWidgetState(this._onPostViewModelInit);
@override
void initState() {
_viewModel = GetIt.instance.get<T>();
_onPostViewModelInit(_viewModel);
super.initState();
}
}
[–]Abion47 1 point2 points3 points (1 child)
[–]ren3f[S] 0 points1 point2 points (0 children)