dart tear-off 是一种更简洁的写法。
tear-off 解释: 一个闭包,它采用与函数相同的参数,并在您调用它时调用底层函数。
如果没有理解不要着急,看几个例子就明白了。
不知道你是否还在这样写 dart
var charCodes = [68, 97, 114, 116];
var buffer = StringBuffer();
// Function:
charCodes.forEach((code) {
print(code);
});
// Method:
charCodes.forEach((code) {
buffer.write(code);
});
// Named constructor:
var strings = charCodes.map((code) => String.fromCharCode(code));
// Unnamed constructor:
var buffers = charCodes.map((code) => StringBuffer(code));
赶快换成 tear-off 的方式吧
var charCodes = [68, 97, 114, 116];
var buffer = StringBuffer();
// Function:
charCodes.forEach(print);
// Method:
charCodes.forEach(buffer.write);
// Named constructor:
var strings = charCodes.map(String.fromCharCode);
// Unnamed constructor:
var buffers = charCodes.map(StringBuffer.new);
如果你开始使用 tear-offs fature,必须确保 你的 dart 2.15(或更高版本)
$ dart --version
在你的 pubspec.yaml,需要更新 SDK version 2.15 或更高。
environment:
sdk: ">=2.15.0 <3.0.0"
举个例子,体会一下用法 。
可能你以前这样写,使用一个 lamda 表达式。
var texts =['IAM17', '天天更新'].map((word) => Text(word)).toList();
使用构造函数 tear-offs ,可以非常简洁。
var texts = ['IAM17', '天天更新'].map(Text.new).toList();
再举个例子
Widget widget;
var type = 'text';
switch (type) {
case "outlined":
widget = OutlinedButton(
onPressed: () {
},
child: const Text("Button"),
);
break;
case "text":
widget = TextButton(
onPressed: () {
},
child: const Text("Button"),
);
break;
default:
widget = ElevatedButton(
onPressed: () {
},
child: const Text("Button"),
);
}
使用 tear-off 可以这样写
var type = 'text';
Function button;
switch (type) {
case "outlined":
button = OutlinedButton.new;
break;
case "text":
button = TextButton.new;
break;
default:
button = ElevatedButton.new;
}
Widget widget = button(
onPressed: () {
},
child: const Text("Button"),
);
还是很简单的,希望你 get 到了,明天见!