使用Dart開發Flutter應用,和Java非常類似,因此對Dart語言特性和Flutter Framework積累足夠的話,便可以寫出更高效和代碼。
分享幾個實用的小技巧,本文參考了 FlutterDartTips ,去除了一些很常見的寫法。
發佈模式判斷
判斷當前環境是否爲發佈模式。
const bool kReleaseMode = bool.fromEnvironment('dart.vm.product')
也可以使用 foundation 提供的常量,實現相同:
import 'package:flutter/foundation.dart';
print('Is Release Mode: $kReleaseMode');
使用這個可以用於控制日誌輸出,比如release模式關閉日誌:
if (isProduction) {
debugPrint = (String message, {int wrapWidth}) => {};
}
詳情=》https://api.flutter.dev/flutter/foundation/kReleaseMode-constant.html
爲Container設置背景圖
都知道 Container 支持child設置展示內容,爲了展示層疊效果,可以使用Column,其實還可以使用decoration間接實現背景圖
Container(
width: double.maxFinite,
height: double.maxFinite,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://bit.ly/2oqNqj9'),
),
),
child: Center(
child: Text(
'Flutter.dev',
style: TextStyle(color: Colors.red),
),
),
),
斷言提示
使用asert進行斷言,通過第二個參數,提供個性化文案,可以讓使用者對斷言要求有一個更清楚的說明
assert(age > 18, "age should be >18");
“鏈式”調用
利用Dart語法,可以簡化方法調用
class Person {
String name;
int age;
Person(this.name, this.age);
void data() => print("$name is $age years old.");
}
void main() {
// Without Cascade Notation
Person person = Person("Richard", 50);
person.data();
person.age = 22;
person.data();
person.name += " Parker";
person.data();
// Cascade Notation with Object of Person
Person("Jian", 21)
..data()
..age = 22
..data()
..name += " Yang"
..data();
}
空值處理
比較常見的一個判斷,當一個變量爲空時進行賦值操作。
// User below
title ??= "Title";
// instead of
if (title == null) {
title = "Title";
}
##最後
上面的小技巧可以收藏記下,關注我會分享更多