[TOC]
下面的最佳實踐適用于為類聲明構造函數。
## 盡可能使用初始化的形式。
許多字段直接從構造函數參數初始化,如:
以下是不推薦的寫法:
~~~
class Point {
num x, y;
Point(num x, num y) {
this.x = x;
this.y = y;
}
}
~~~
以下是推薦的寫法:
~~~
class Point {
num x, y;
Point(this.x, this.y);
}
~~~
構造函數參數前的this.語法稱為“初始化形式”。你不能總是利用它。特別是,使用它意味著參數在初始化列表中不可見。但是,當你需要這樣做時,你應該這樣做。
## 不要鍵入注釋初始化的形式。
如果構造函數參數使用this.初始化一個字段,那么該參數的類型被理解為與字段的類型相同。
以下是推薦的寫法:
~~~
class Point {
int x, y;
Point(this.x, this.y);
}
~~~
不要使用以下寫法:
~~~
class Point {
int x, y;
Point(int this.x, int this.y);
}
~~~
## 對于空的構造函數體使用;而不是{}。
在Dart中,帶有空主體的構造函數只能以分號結束。(事實上,const構造函數需要它。)
以下是推薦的寫法:
~~~
class Point {
int x, y;
Point(this.x, this.y);
}
~~~
以下是不推薦的寫法:
~~~
class Point {
int x, y;
Point(this.x, this.y) {}
}
~~~
## 不要使用new
Dart2使new 關鍵字可選。即使在Dart 1中,它的含義也一直不清楚,因為工廠構造函數意味著新的調用可能仍然不會返回新的對象。
為了減少遷移的痛苦,這種語言仍然允許使用new,但是要考慮到它已被棄用,并將其從代碼中刪除。
以下是推薦的寫法:
~~~
Widget build(BuildContext context) {
return Row(
children: [
RaisedButton(
child: Text('Increment'),
),
Text('Click!'),
],
);
}
~~~
以下是不推薦的寫法:
~~~
Widget build(BuildContext context) {
return new Row(
children: [
new RaisedButton(
child: new Text('Increment'),
),
new Text('Click!'),
],
);
}
~~~
## 不要過多的使用const。
在表達式必須為常量的上下文中,const關鍵字是隱式的,不需要編寫,也不應該編寫。這些上下文是內部的任何表達式:
* 一個const字面量集合。
* 一個const構造函數調用
* 一個元數據注釋。
* const變量聲明的初始化器。
* 在switch-case表達式中——在case的冒號(:)之前,而不是case的主體。
(默認值不包括在這個列表中,因為Dart的未來版本可能會支持非常量默認值。)
Basically, any place where it would be an error to write new instead of const, Dart 2 allows you to omit the const.
基本上,任何使用new而不是const的地方都有可能出現錯誤,Dart 2允許你省略const。
>**譯者注**:以上這句的翻譯有點兒拗口。其實通俗的解釋是這樣的:比如顏色的rgb值[255, 0, 0]這其實是new初始化了一個數組(list集合),但是如果在之前加了const [255, 0, 0]就不對了
以下是正確寫法:
~~~
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]),
];
~~~