Flutter Key

image.png

LocalKey

应用于拥有相同父 Element 的小部件进行比较的情况

1. UniqueKey

A key that is only equal to itself

2. ValueKey

A key that uses a value of a particular type to identify itself

3. ObjectKey

A key that takes its identity from the object used as its value

/**
 * Check whether two references are to the same object.
 */
external bool identical(Object a, Object b);

4.PageStorageKey

当你有一个滑动列表,你通过某一个 Item 跳转到了一个新的页面,当你返回之前的列表页面时,你发现滑动的距离回到了顶部。这时候,给 Sliver 一个 PageStorageKey!它将能够保持 Sliver 的滚动状态。

/// A [ValueKey] that defines where [PageStorage] values will be saved.
///
/// [Scrollable]s ([ScrollPosition]s really) use [PageStorage] to save their
/// scroll offset. Each time a scroll completes, the scrollable's page
/// storage is updated.
///
/// [PageStorage] is used to save and restore values that can outlive the widget.
/// The values are stored in a per-route [Map] whose keys are defined by the
/// [PageStorageKey]s for the widget and its ancestors. To make it possible
/// for a saved value to be found when a widget is recreated, the key's values
/// must not be objects whose identity will change each time the widget is created.
///
/// For example, to ensure that the scroll offsets for the scrollable within
/// each MyScrollableTabView below are restored when the [TabBarView]
/// is recreated, we've specified [PageStorageKey]s whose values are the
/// tabs' string labels.

TabBarView(
   children: myTabs.map((Tab tab) {
     MyScrollableTabView(
       key: PageStorageKey(tab.text), // like 'Tab 1'
       tab: tab,
     ),
   }),
 )

Demo:

String a = 'ab' + 'c';
  String b = 'abc';
  UniqueKey uKey1 = new UniqueKey();
  UniqueKey uKey2 = new UniqueKey();
  ValueKey vKey1 = new ValueKey('abc');
  ValueKey vKey2 = new ValueKey('ab' + 'c');
  ObjectKey oKey1 = new ObjectKey('abc');
  ObjectKey oKey2 = new ObjectKey('ab' + 'c');

  print(
      '${a == b} ${identical(a, b)} UniqueKey:${uKey1 == uKey2} ValueKey:${vKey1 == vKey2} ObjectKey:${oKey1 == oKey2}');

结果:

true false UniqueKey:false ValueKey:true ObjectKey:false

GlobalKey

能够跨 Widget 访问状态,GlobalKey会在组件Mount阶段把自身放到一个Map里面缓存起来,代价较昂贵,谨慎使用

你可能感兴趣的:(Flutter Key)