I'm getting a runtime error from a Dart generic function:
Widget card = widget.cardBuilder(item);
Which generates:
type '(Contact) => Widget' is not a subtype of type '(DeletableItem) => Widget'
The Contact class is defined as
class Contact
implements DeletableItem
{
I then have a method:
class UndoableListView<T extends DeletableItem>
{
List<T> children;
final Widget Function(T item) cardBuilder;
And this is where the runtime error occurs
Widget buildItem(BuildContext context, int index) {
T item = children[index];
Widget card = widget.cardBuilder(item); <<<<< error thrown here.
I'm clearly mis-understanding something with how generics work.
Contact clearly extends DeleteableItem.
So what have I done wrong?
Contact
doesn't implementDeletableItem
, but rather that the whole function itself has a different signature since(Contact) => Widget
cannot be cast to(DeletableItem) => Widget
. Without seeing more code, it's hard to propose a fix. Can you show the context in whichbuildItem
is being used? – ZuberContact
is not a subtype ofDeletableItem
, but that the function typeWidget Function(Contact)
is not a subtype of the function typeWidget Function(DeletableItem)
. Function types are contravariant in their parameter types (a function type can only a subtype of another function type if the parameter types of the first function are supertypes of the parameter types of the second function). So, this is working as intended. – Seligmann