flutter的tear-off是啥玩意,进来看看你就明白了

1,094 阅读2分钟

可能有的同学在ide会看到一些提示:

Don't create a lambda when a tear-off will do

这个意思就是叫你不用创建一个匿名函数,用tear-off就行了。

那么tear-off是啥呢?

看看 DartLang 文档解释:

17.21 Property ExtractionFunction objects derived from members via closurization are colloquially known as tear-offs.定义:通过闭包从成员派生的函数对象通俗的成为:tear-offProperty extractionallows for a member to be accessed as a property rather than a function. A property extraction can be either:解释:简单来说就是:允许类成员作为属性进行访问An instance method closurization, which converts a method into a function object (17.21.3). // 一个闭包的实例方法,会将方法转换为函数对象A getter invocation, which returns the result of invoking of a getter method (17.21.1).//或者一个Getter方法,会返回getter方法触发的结果

换句话说,“tear-off”是用于描述从函数或方法名称生成函数对象的行为的术语。

它们相当于其他语言中的函数指针或成员函数指针。当您想将函数或方法直接用作回调时,您将使用tear-off。

例如换句话说,“tear-off”是用于描述从函数或方法名称生成函数对象的行为的术语。它们相当于其他语言中的函数指针或成员函数指针。

当您想将函数或方法直接用作回调时,您将使用tear-off。

例如:

class Foo {
  int value;

  Foo(this.value);

  int add(int other) => value + other;
  int multiply(int other) => value * other;
}

void main() {
  var foo = Foo(5);

  // `foo.add` is an instance method tear-off.  It is equivalent to:
  // `(int other) => foo.add(other)`
  var someOperation = foo.add;  //注意看这行,将方法作为函数对象传递
  print(someOperation(8)); // Prints: 13

  someOperation = foo.multiply;
  print(someOperation(8)); // Prints: 104
}

还没看明白?

这个例子够简单了吧:

有人可能会写:

ElevatedButton(
  onPressed: () { myHandler(); }
)

其实只用这样写就可以了

onPressed : myHandler //

ElevatedButton(
  onPressed: myHandler <-- myHandler is a tear-off
)

总结:很多时候布局UI的时候,比如一个ElavatedButton需要点击方法,我们多数情况下是提供这个方法而不是调用这个方法,这样widget就可以在用到的时候才会去调用,所以我们需要的只是将方法作为参数或者函数对象传递,而不用写一个匿名函数,注意前提是函数参数和返回值类型要一致