0. 用Widgets 代替函数
函数代码
Widget _buildFooterWidget() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text('This is the footer '),
);
}.
Widget 代码
class FooterWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text('This is the footer '),
);
}
}
widgets 可以重复使用。私人函数只能使用一次,并且框架不知道函数,但是可以看到类。
1. 不在List中使用引用
//错误
List a = [1,2,3,4];
List b;
b = a;
a.remove(1);
print(a); // [2,3,4]
print(b); // [2,3,4]
每当您尝试调用列表 a 的任何方法时,都会自动调用列表 b。 如 a.remove (some) ; 也会从列表 b 中删除该项;
List a = [1,2,3,4];
List b;
b = jsonDecode(jsonEncode(a));
a.remove(1);
print(a); // [2,3,4]
print(b); // [1,2,3,4]
2. 使用 for/while 代替 foreach/map
效率比对
3. 利用字符串模板内插
// 不当
var discountText = 'Hello, ' + name + '! You have won a brand new ' + brand.name + 'voucher! Please enter your email to redeem. The offer expires within ' + timeRemaining.toString() ' minutes.';
// 适当
var discountText = 'Hello, $name! You have won a brand new ${brand.name} voucher! Please enter your email to redeem. The offer expires within ${timeRemaining} minutes.';
4. 用nil 代替 const container()
// good
text != null ? Text(text) : const Container()
// Better
text != null ? Text(text) : const SizedBox()
// BEST
text != null ? Text(text) : nil
or
if (text != null) Text(text)