I'm reading the documentation on Isolate.spawn<T>, and it mentions "instance method tear-off". I don't know what that is, and I could not find where else it's explained. What is a tear off?
The function must be a top-level function or a static method that can be called with a single argument, that is, a compile-time constant function value which accepts at least one positional parameter and has at most one required positional parameter. The function may accept any number of optional parameters, as long as it can be called with just a single argument. The function must not be the value of a function expression or an instance method tear-off.
It's also used a lot in this github issue: Support method/function overloads.
The Dart Language Specification explains:
17.21 Property Extraction
Property extraction allows 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). Or
- A getter invocation, which returns the result of invoking of a getter method (17.21.1).
Function objects derived from members via closurization are colloquially known as tear-offs.
The Effective Dart guide also refers to tear-offs and describes them with less jargon:
If you refer to a method on an object but omit the parentheses, Dart gives you a “tear-off”—a closure that takes the same parameters as the method and invokes it when you call it.
In other words, "tear-off" is the term used to describe the act of making a function object from a function or method name. They are the equivalent of function pointers or pointers-to-member-functions in other languages. You would use a tear-off when you want to use a function or method directly as a callback. For example:
class Foo {
final int value;
const Foo(this.value);
int add(int other) => value + other;
int multiply(int other) => value * other;
}
void main() {
const 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: 40
}
(This eventually should be explained on the Dart Language Tour too.)
I guess Google developers had realized that this was an area of confusion, so they made a neat video just last week: Tear-offs | Decoding Flutter
For example, they suggest, instead of:
ElevatedButton(
onPressed: () { myHandler(); }
)
Use:
ElevatedButton(
onPressed: myHandler <-- myHandler is a tear-off
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With