在 dart 中使用 tear-off

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 到了,明天见!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IAM17前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值