flutter中的key是用来标识[Widget]s, [Element]s and [SemanticsNode]s在某个上下文环境中的唯一性用的.
具体参照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之前关联widget的key是相等的。Keys must be unique amongst the [Element]s with the same parent.
同一个父节点下面的各个子节点 [Element]s的key必须是互不相同的。Subclasses of [Key] should either subclass [LocalKey] or [GlobalKey].
如要实现[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会提供一个默认的无参数构造方法。
/// 言下之意,如果你申明了,那么就不会提供这个无参数的构造方法了。
/// 这里申明一个名为empty的默认无参数构造方法
/// const关键字是用来返回const对象给声明为const的参数赋值用的。如果没有const关键字,则给声明为const的参数赋值时,会报错 Error: Cannot invoke a non-'const' constructor where a const expression is expected.
/// 但是const构造方法并不总是返回const对象,当给声明为const或final的参数赋值时,会返回一个const对象,如果是给可变参数赋值,则返回一个可变的对象。
@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');
};