.foo 點簡寫語法可省略型別名稱,只要編譯器能從上下文推斷出目標型別,就能撰寫更精簡的 Dart 程式碼。存取列舉值、靜態成員、建構函式時,不需完整寫出 型別.foo。
簡單來說:點簡寫允許運算式以以下形式開頭,後續還能鏈式呼叫其他操作:
- 識別項
.myValue - 建構函式
.new() - 常數建立
const .myValue()
範例
enum Status { none, running, stopped, paused }
class Point {
final int x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
}
void main() {
// 具名建構簡寫
Point origin = .origin(); // 等同 Point.origin()
// 列舉簡寫
Status currentStatus = .running; // 等同 Status.running
// 靜態方法簡寫
int port = .parse('8080'); // 等同 int.parse('8080')
}Code language: Dart (dart)
上下文型別(Context type)
點簡寫仰賴上下文型別,讓編譯器推斷對應的型別成員。
上下文型別:依據運算式所在位置,Dart 預期此處具備的資料型別。
範例:Status currentStatus = .running
編譯器知道變數需要 Status 型別,因此將 .running 解析為 Status.running。
詞彙結構與語法
靜態成員簡寫是以 . 開頭的運算式。當上下文能夠確定型別時,可簡寫存取:靜態成員、建構函式、列舉常數。
適用場景
1. 列舉
進行指派、switch 比對時,列舉型別十分明確,很適合使用簡寫:
enum LogLevel { debug, info, warning, error }
String colorCode(LogLevel level) {
return switch (level) {
.debug => 'gray',
.info => 'blue',
.warning => 'orange',
.error => 'red',
};
}
void main() {
// 呼叫
String warnColor = colorCode(.warning); //自動辨識為 LogLevel.warning
}Code language: Dart (dart)
2. 具名建構 / 工廠建構
支援泛型類別建構函式傳入型別參數:
class Point {
final double x, y;
const Point(this.x, this.y);
const Point.origin() : x = 0, y = 0;
factory Point.fromList(List<double> list) => Point(list[0], list[1]);
}
void main() {
Point origin = .origin();
Point p1 = .fromList([1.0, 2.0]);
// 泛型類別
List<int> intList = .filled(5, 0); // List.filled(5,0)
}Code language: Dart (dart)
3. 無參數建構 .new
.new 簡寫呼叫類別預設的無名建構函式,適合狀態類大量初始化欄位,並可自動推斷泛型參數:
// 簡寫前
late final AnimationController _animationController = AnimationController(vsync: this);
final ScrollController _scrollController = ScrollController();
// 簡寫後
late final AnimationController _animationController = .new(vsync: this);
final ScrollController _scrollController = .new();
final GlobalKey<ScaffoldMessengerState> scaffoldKey = .new();
Map<String, Map<String, bool>> properties = .new();Code language: Dart (dart)
4 靜態成員(靜態方法、靜態欄位)
int httpPort = .parse('80'); // int.parse('80')
BigInt bigIntZero = .zero; // BigInt.zeroCode language: Dart (dart)
5 常數運算式
在常數上下文當中,只要目標成員屬於編譯期常數,就能使用簡寫:
enum Status { none, running }
class Point {
final double x, y;
const Point(this.x, this.y);
const Point.origin() : x = 0.0, y = 0.0;
}
const Status defaultStatus = .running;
const Point myOrigin = .origin();
const List<Point> keyPoints = [.origin(), .new(1.0, 1.0)];Code language: Dart (dart)
鏈式呼叫
簡寫後可以鏈式呼叫實體方法與屬性;編譯器會先透過上下文解析簡寫目標,後續鏈式呼叫的回傳值必須符合相容型別:
String lowerH = .fromCharCode(72).toLowerCase();
// String.fromCharCode(72).toLowerCase()
print(lowerH); // hCode language: JavaScript (javascript)
void main() {
String lowerH = .fromCharCode(72).toLowerCase();
// String.fromCharCode(72).toLowerCase()
print(lowerH); // h
}Code language: Dart (dart)
D:\dartdemo\firstdart>dart run
Building package executable...
Built firstdart:firstdart.
h
Code language: CSS (css)
Dot shorthands(點簡寫)
Previous: 列舉
Next: 擴充方法(Extension methods)