How do I use Dart extension functions?

There is an official video by the Flutter team about extension methods now.

Static extension members

Here is an intuitive example of how extension methods work:

extension FancyNum on num {
  num plus(num other) => this + other;

  num times(num other) => this * other;

I simply extend num here and add methods to the class. This could be used like this:

print(; // Equal to "5 + 3".
print(5.times(8)); // Equal to "5 * 8".
print(; // Equal to "(2 + 1) * 3".

Note that the name FancyNum is optional and the following is valid too:

extension on num {}

When you use your extension in another file, you must give it a name.

The extension above will make use of implicit extension member invocations as you do not have to explicitly declare your num to be a FancyNum.

You can also explicitly declare your extension, but this is not needed in most cases:


Flex childCount

The desired behavior from the question can be achieved by extending Row or Column, or even better: you can extend Flex, which is the super class of Row and Column:

extension ExtendedFlex on Flex {
  int get childCount => this.children.length;

this. can also be omitted if children is not defined in the current lexical scope of childCount, which means that => children.length is also valid.

With this static extension of Flex imported, you can call it on any Flex, i.e. also on every Row and Column.
Row(children: const [Text('one'), Text('two')]).childCount will evaluate to 2.

Leave a Comment