如何使用Dart扩展功能? [英] How do I use Dart extension functions?

查看:69
本文介绍了如何使用Dart扩展功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dart 2.6引入了一种新的语言功能,称为 静态扩展成员

但是,我不太了解如何使用它。

Dart 2.6 introduces a new language feature called "static extension members".
However, I do not quite understand how to use it.

我想轻松获得 Row childCount >列,即使用 row.childCount 代替 row.children.length

I would like to easily get the childCount of a Row or Column, i.e. use row.childCount instead of row.children.length:

void main() {
  final row = Row(children: const [Text('one'), Text('two')]), 
      column = Column(children: const [Text('one'), Text('two'), Text('three')]);

  print(row.childCount); // Should print "2".

  print(column.childCount); // Should print "3".
}

我尝试执行以下操作,但这是语法错误:

I tried to do the following, but it is a syntax error:

Row.childCount() => this.children.length;

Column.childCount() => this.children.length;


推荐答案

有一个 Flutter团队提供的有关扩展方法的官方视频

以下是扩展方法的工作方式的直观示例:

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;
}

我只是扩展 num 在这里,并将方法添加到类中。可以这样使用:

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

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

请注意,名称 FancyNum 是可选的,以下内容也同样有效:

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.

以上扩展名将使用隐式扩展成员调用,因为您不必显式声明 num 成为 FancyNum

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:

print(FancyNum(1).plus(2));



Flex childCount



所需的行为可以通过扩展 Row Column 来解决这个问题,甚至更好:您可以扩展 Flex ,这是超类 的值:

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。可以如果在当前 childCount 的当前词法范围内未定义 children ,也将省略,这表示 => 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.

使用此静态扩展名已导入的 Flex 中的任何一个,您可以在任何 Flex 上调用它,也可以在每个 Row上调用它

行(子代:const [Text('one'),Text ('two')])。childCount 的值为 2

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.

这篇关于如何使用Dart扩展功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆