source
原作者:Jose Alba,所在团队在维护Flutter material library。
三个有用的Dart pattern帮助我成为更好的Flutter developer。
- 条件判断赋值:
boolean ? widget : widget - 合并widget到集合:
for() ...[] - 立即调用匿名函数:
(){}()
1. 条件判断赋值
appBar: AppBar(
title: Text(
Randome.nextBool()
? 'Vegetarian'
: 'Non-Vegetarian Food'),
),
2. 合并widget为集合
for() ...[],用展开操作符...把一些列widgets合并进一个已存在的集合中。
children: [
Container(),
for(final food in foods)...[
if (isVegetarian == food.isVegetarian)
ListTile(title: Text(food.name)),
SizedBox(height: 50.0)
],
]
展开操作符...要求 Dart SDK >= 2.3.0
collection operators
spread operators
3. 立即调用匿名函数
(){}()是Dart版本的IIFE(immediately invoked function expression).
这个模式在解决一个widget有多种输出的情况下很有用。
color: (){
switch(getRandomElement(foods.name)) {
case 'apple':
return Colors.green;
case 'nuts':
return Colors.blue;
case 'eggs':
return Colors.yellow;
default:
return Colors.transparent;
}
}()
总结
译者注: collection operators
Dart 2.3 引入了collection if 和 collection for,可以用if 和 for来创建集合。
var nav = [
'Home',
"Furnitur",
'Plants',
if (promoActive) 'Outlet'
];
var listOfInts = [1, 2, 3];
var listOfStrings = [
'#0',
for (var i in listOfInts) '#$i'
];
assert(listOfStrings[1] == '#1');
spread operators Dart 2.3 还引入了...和...? (null-aware spread operator),使可以用简洁的方式插入多个元素到一个collection。
var list;
var list2 = [0, ...?list];
asset(list2.length == 1);
官方更详细的关于collection operators和spread operators请查看下面链接: github.com/dart-lang/l…