Extension methods for generic types
Since Dart 2.7 it is possible to add functionalities to existing libraries. If a class is missing a method you would like to use, you can just extend that class with your own implementation of such a method.
You do not need to create a pull request on the code of the library you want to update, you can keep the new functionality locally to your code. For example, if you need to format a Duration
so that it shows days, hours, minutes, and seconds in the following format: dd:HH:MM:SS
, you can define an extension method on Duration
:
Extension on generic types
You can not only extend a “concrete” type like Duration
. You can also extend the functionalities of a generic type, so that all its concrete instances (and all subclasses) obtain the new extension method.
For instance, if we want to add a firstWhereOrNull
to List
, where we either return the first element in the list that satisfies a condition, or null
if none satisfies that condition, we can create an extension method like this:
By creating the extension method on the generic Iterable<E>
we add it to all concrete types of all subclasses of Iterable
, like Queue, List, and Set, thus also to List<String>
.
Leave a comment