空处理
?? ?. 的使用
如果你还不清楚?? ?.
的意思=> Dart 如何优雅的避空
- 推荐使用
??
将null
转换为需要的值
Text(title ?? '')
if(title?.isEmpty ?? true){
// ...
}
- 不推荐使用
==
赋值
// 不推荐
if(title?.isEmpty == true){
// ...
}
- 解析
json
实体数据null的处理
// 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"] ?? [],
字符串相关
使用临近字符字的方式连接字面量字符串
不需要使用 +
来连接它们。应该像 C
和 C++
一样,只需要将它们挨着在一起就可以了。这种方式非常适合不能放到一行的长字符串的创建:
raiseAlarm(
'ERROR: Parts of the spaceship are on fire. Other '
'parts are overrun by martians. Unclear which are which.');
- 而不是类似于Java使用
+
连接
// 不推荐
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创建集合的推荐姿势:
- 集合字面量
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;
}
- 使用
.isEmpty
和.isNotEmpty
替代.length
if (nameList.isEmpty) // nameList.length == 0
// 使用 ?? 替代 ==
if (nameList?.isEmpty ?? true) // nameList == null || nameList.length == 0
隐式new
、const
- new 关键字成为可选项
Widget build(BuildContext context) {
return Row(
children: [
RaisedButton(
child: Text('Increment'),
),
Text('Click!'),
],
);
}
- 弃用和删除 new
Widget build(BuildContext context) {
return new Row(
children: [
new RaisedButton(
child: new Text('Increment'),
),
new Text('Click!'),
],
);
}
- primaryColors 是
const
, 它的内容const
关键字是隐式的,不需要写:
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]),
];
=>
箭头语法
=>
这种箭头语法是一种定义函数的方法,该函数将在其右侧执行表达式并返回其值
-
get
、set
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!'));
网友评论