flutter中的key是用來標識[Widget]s, [Element]s and [SemanticsNode]s在某個上下文環(huán)境中的唯一性用的.
具體參照widget中key屬性的說明亡哄。A new widget will only be used to update an existing element if its key is
the same as the key of the current widget associated with the element.
要更新一個element碗啄,新提供的widget的key必須同element之前關聯(lián)widget的key是相等的越走。Keys must be unique amongst the [Element]s with the same parent.
同一個父節(jié)點下面的各個子節(jié)點 [Element]s的key必須是互不相同的。Subclasses of [Key] should either subclass [LocalKey] or [GlobalKey].
如要實現(xiàn)[Key]的子類博秫,應當繼承自 [LocalKey] 或者 [GlobalKey]儿倒。
@immutable
abstract class Key {
/// Construct a [ValueKey<String>] with the given [String].
///
/// This is the simplest way to create keys.
/// 這里用關鍵字factory是因為要返回Key的子類ValueKey類型
const factory Key(String value) = ValueKey<String>;
/// Default constructor, used by subclasses.
///
/// Useful so that subclasses can call us, because the [new Key] factory
/// constructor shadows the implicit constructor.
/// 文檔說如果你沒有申明構造器饲趋,那么dart會提供一個默認的無參數(shù)構造方法妓雾。
/// 言下之意,如果你申明了玄窝,那么就不會提供這個無參數(shù)的構造方法了牵寺。
/// 這里申明一個名為empty的默認無參數(shù)構造方法
/// const關鍵字是用來返回const對象給聲明為const的參數(shù)賦值用的。如果沒有const關鍵字恩脂,則給聲明為const的參數(shù)賦值時帽氓,會報錯 Error: Cannot invoke a non-'const' constructor where a const expression is expected.
/// 但是const構造方法并不總是返回const對象,當給聲明為const或final的參數(shù)賦值時俩块,會返回一個const對象黎休,如果是給可變參數(shù)賦值,則返回一個可變的對象典阵。
@protected
const Key.empty();
}
PS:
關于factory關鍵字
Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype.
關鍵字factory 用于返回的實例不總是本類的時候使用奋渔,比如從緩存返回一個實例,或返回一個子類的實例壮啊。關于const關鍵字
class TestKey extends LocalKey {
const TestKey() : super();
}
- 給const變量賦值
const TestKey aKey = TestKey();
const TestKey bKey = TestKey();
if(identical(aKey, bKey)){
/// 會走到這里
print('identical $aKey , $bKey');
}
else{
print('not identical $aKey , $bKey');
};
- 給可變變量賦值
TestKey aKey = TestKey();
TestKey bKey = TestKey();
if(identical(aKey, bKey)){
print('identical $aKey , $bKey');
}
else{
/// 會走到這里
print('not identical $aKey , $bKey');
};