void Function(int) isn’t a valid override of void Function(dynamic)

void Function(int x) normally isn’t a valid override of void Function(dynamic x) because the int version is not substitutable for the dynamic version.

What are the allowed inputs to Parent<dynamic>.method? Anything.

What are the allowed inputs to Child.method? Just ints.

Such an override therefore could violate the contract of Parent<dynamic>‘s interface. (For example, what if you had an instance of Child and passed it to something that expected Parent<dynamic>, which then invoked method('not an int') on it?)

(Note that this is not specific to method overrides. In general, a function that takes a narrower type cannot be used where a function that takes a wider type is expected, even if the narrower type derives from the wider type.)

Dart does allow you to use the covariant keyword to suppress the static type error and explicitly allow the override, but be aware that doing so isn’t necessarily type-safe, and you would be responsible for ensuring that you don’t get type errors at runtime.

Further reading: Covariance and contravariance (computer science) from Wikipedia

Leave a Comment