Dart 一些高效用法实例

2020-01-09  本文已影响0人  NightRainBreeze

空处理

?? ?. 的使用

如果你还不清楚?? ?.的意思=> Dart 如何优雅的避空

Text(title ?? '')

if(title?.isEmpty ?? true){
  // ...
}
// 不推荐
if(title?.isEmpty == true){
  // ...
}
// list为null的处理赋值空list
moreList = List<SRItemModel>.from(map["moreList"]?.map((it) => SRItemModel.fromJsonMap(it)) ?? [])
// 字段为null的处理
goodsName = map["goodsName"] ?? '',
specName = map["specName"] ?? '',
count = map["goodsQty"] ?? 0,
list = map["list"] ?? [],

字符串相关

使用临近字符字的方式连接字面量字符串
不需要使用 + 来连接它们。应该像 CC++ 一样,只需要将它们挨着在一起就可以了。这种方式非常适合不能放到一行的长字符串的创建:

raiseAlarm(
    'ERROR: Parts of the spaceship are on fire. Other '
    'parts are overrun by martians. Unclear which are which.');
// 不推荐
raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' +
    'parts are overrun by martians. Unclear which are which.');
'Hello, $name! You are ${year - teacher.birth} years old.';

// 不要使用不必要的大括号
'Hello, ${name}';

// 更不要再使用这种方式了, 使用$会看起来更连贯
'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';

集合相关

Dart高效之操作集合

首先来看一下dart创建集合的推荐姿势:

var points = []; // var points = List();
var addresses = {}; // var addresses = Map();
var points = <Point>[]; // var points = List<Point>();
var addresses = <String, Address>{}; // var addresses = Map<String, Address>();
List<int> singletonList(int value) {
  var list = <int>[]; // List<int> list = [];
  list.add(value);
  return list;
}
if (nameList.isEmpty)  // nameList.length == 0

// 使用 ?? 替代 ==
if (nameList?.isEmpty ?? true)  // nameList == null || nameList.length == 0

隐式newconst

Widget build(BuildContext context) {
  return Row(
    children: [
      RaisedButton(
        child: Text('Increment'),
      ),
      Text('Click!'),
    ],
  );
}
Widget build(BuildContext context) {
  return new Row(
    children: [
      new RaisedButton(
        child: new Text('Increment'),
      ),
      new Text('Click!'),
    ],
  );
}
const primaryColors = [
  Color("red", [255, 0, 0]),
  Color("green", [0, 255, 0]),
  Color("blue", [0, 0, 255]),
];
const primaryColors = const [
  const Color("red", const [255, 0, 0]),
  const Color("green", const [0, 255, 0]),
  const Color("blue", const [0, 0, 255]),
];

=>箭头语法

=>这种箭头语法是一种定义函数的方法,该函数将在其右侧执行表达式并返回其值

class Circle {
  num radius;
  int _width;

  Circle(this.radius, this._width);

  num get area => pi * radius * radius;
  num get circumference => pi * 2.0 * radius;
  set width(int width) => _width = width;
}
bool hasEmpty = aListOfStrings.any((s) {
  return s.isEmpty;
});
bool hasEmpty = aListOfStrings.any((s) => s.isEmpty);

级连..

要对同一对象执行一系列操作,请使用级联..

var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
// 级连
querySelector('#confirm')
..text = 'Confirm'
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
上一篇 下一篇

猜你喜欢

热点阅读