I have a variable defined as type:-
final Future Function(BuildContext context, FormModel model) onSubmitCallBack;
I am assigning to it a function which takes 2 parameters of type BuildContext and Institute, and returns Future.
Note that Institute is a Subclass of FormModel.
There is no error at compile time. But at runtime I get this error.
Expected a value of type '(BuildContext, FormModel) => Future', but got one of type '(BuildContext, Institute) => Future'
Any Ideas why? I expected this to run since Institute is subclass of FormModel.
The FormModel and Institute class:
class FormModel{
const FormModel();
}
class Institute extends FormModel {
final int? id;
final String name;
final String? addedOn;
final String? updateOn;
const Institute({
this.id,
required this.name,
this.addedOn,
this.updateOn
});
}
CodePudding user response:
This is because every Institite
is a FormModel
but not every FormModel
is an Institute
.
Consider having yet another extension like class Study extends FormModel
. In such case your assignment is unsafe because your callback implementation accepts only Institute
but yet it can be provided with Study
which would simply break.
In other words, you expect this to work (pseudocode):
final Future Function(BuildContext context, FormModel model) onSubmitCallBack;
final Future Function(BuildContext ctx, Institute model) instituteCallback;
onSubmitCallback = instituteCallback;
onSubmitCallback(ctx,new Study()); /// WHOOOOOOPS
now you have a problem as Study
is not an Institute
and yet it would have to be passed as such.