核心: static 修飾
members, final 修飾variables, const修飾value
static
static 意味著成員是類變量,?不是實(shí)例變量。
final
1.在運(yùn)行時(shí)獲得值, 且只能單次賦值即一旦賦值final就不能改變
2.聲明的變量,不賦值是不可以使用的。
const
1.需要在編譯期就能計(jì)算出來(lái)的數(shù)據(jù)創(chuàng)建
2.const 創(chuàng)建的控件不會(huì)重新構(gòu)建
3.const 聲明構(gòu)造器就是告訴 Flutter 如果遇到了一個(gè)不可變的構(gòu)造器,這就是一個(gè)不可變對(duì)象,可以進(jìn)行復(fù)用。注意const 構(gòu)造器需要字段為final修飾
應(yīng)用
- 單利實(shí)現(xiàn)
class Singleton {
//當(dāng)你使用factory關(guān)鍵詞時(shí),你能控制在使用構(gòu)造函數(shù)時(shí),并不總是創(chuàng)建一個(gè)新的該類的對(duì)象
//比如它可能會(huì)從緩存中返回一個(gè)已有的實(shí)例,或者是返回子類的實(shí)例。
factory Singleton() => _single;//
static final _single = Singleton._init();
Singleton._init(){}
}
- 控件構(gòu)建
child: const Text('加 const');
VS
child: Text('不加 const');
- const 構(gòu)造器
final T data;
final Widget child;
const ChangeNotifierProvider({Key key, this.data, this.child})