繁体   English   中英

如何使用 Dart 扩展功能?

[英]How do I use Dart extension functions?

Dart 2.6 引入了一个名为“ static 扩展成员”的新语言功能。
但是,我不太明白如何使用它。

我想轻松获得RowColumnchildCount ,即使用row.childCount而不是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".
}

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

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

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

Flutter 团队现在有一个关于扩展方法的官方视频

Static 扩展成员

这是扩展方法如何工作的直观示例:

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

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

我只是在这里扩展num并向 class 添加方法。 这可以像这样使用:

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是可选的,以下也是有效的:

extension on num {}

当你在另一个文件中使用你的扩展名时,你必须给它一个名字。


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

您也可以显式声明您的扩展,但在大多数情况下不需要这样做:

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

弹性子数

问题的期望行为可以通过扩展RowColumn来实现,甚至更好:您可以扩展Flex ,这是RowColumn的超级 class :

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

this. 如果 childCount 的当前词法childCount中没有定义children ,也可以省略,这意味着=> children.length也是有效的。


使用这个static 扩展Flex导入,您可以在任何Flex上调用它,即也可以在每个RowColumn上调用。
Row(children: const [Text('one'), Text('two')]).childCount将评估为2

Dart 2.7 引入了新的扩展方法概念。

https://dart.dev/guides/language/extension-methods

extension ParseNumbers on String {
    int parseInt() {
        return int.parse(this);
    }
    double parseDouble() {
        return double.parse(this);
    }
}
main() {
    int i = '42'.parseInt();
    print(i);
}

扩展可以有泛型类型参数。 对于以下示例显示多个适用扩展可用时的隐式扩展分辨率。

extension SmartIterable<T> on Iterable<T> {
  void doTheSmartThing(void Function(T) smart) {
    for (var e in this) smart(e);
  }
}
extension SmartList<T> on List<T> {
  void doTheSmartThing(void Function(T) smart) {
    for (int i = 0; i < length; i++) smart(this[i]);
  }
}
...
  List<int> x = ....;
  x.doTheSmartThing(print);

这里两个扩展都适用,但SmartList扩展比SmartIterable扩展更具体,因为 List <: Iterable<dynamic>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM