current position:Home>Brief introduction to fluent key

Brief introduction to fluent key

2021-08-27 08:59:11 __ white

This is my participation 8 Yue Gengwen challenges 23 God , Check out the activity details :8 Yuegengwen challenge

Flutter Key

When widget stay widget tree When moving in ,key You can keep its state .

key Can be used to retain the user's scroll position , Or keep the state when modifying the collection .

When do you need Key

If you haven't used it key, Explain that you may not need to use key.

That's exactly what happened , Most of the time , We don't need to use key.

But if you find yourself needing to add , Delete or reorder the same type of... In a certain state widget When you gather , Maybe you need to use key It's time .

Let's start with an official example key The role of , Exchange two different colors widget

class KeyStudy extends StatefulWidget {
  _KeyStudyState createState() => _KeyStudyState();

class _KeyStudyState extends State<KeyStudy> {
  List<Widget> tiles;

  void initState() {
    tiles = [StatelessColorfulWidget(), StatelessColorfulWidget()];

  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: tiles,
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.refresh),
          onPressed: () {
            setState(() {
              tiles.insert(1, tiles.removeAt(0));

class StatelessColorfulWidget extends StatelessWidget {
  static List<Color> colorList = [, Colors.yellow,];
  final defaultColor = colorList[new Random().nextInt(3)];

  Widget build(BuildContext context) {
    return Container(
      width: 200,
      height: 200,
      color: defaultColor,

 Copy code 

The code is not complicated , We first define a stateless widget:StatelessColorfulWidget ,

Then place... Side by side on the page 2 It's time widget.

Switch the two... By clicking the button widget The location of .

It looks normal , The operation also meets our expectations , At this point we are going to StatelessColorfulWidget from StatelessWidget Switch to StatefulWidget, And store the color in state in ,

class StatefulColorfulWidget extends StatefulWidget {
  StatefulColorfulWidget({Key key}) : super(key: key);

  _StatefulColorfulWidgetState createState() => _StatefulColorfulWidgetState();

class _StatefulColorfulWidgetState extends State<StatefulColorfulWidget> {
  Color defaultColor;

  void initState() {
    defaultColor = StatelessColorfulWidget.colorList[new Random().nextInt(3)];

  Widget build(BuildContext context) {
    return Container(
      width: 200,
      height: 200,
      color: defaultColor,
 Copy code 

The code is still not complex , And then use StatefulColorfulWidget replace tiles Medium StatelessColorfulWidget, Take a look at the effect :

  Mechanism , It is suggested to save the pictures and upload them directly

I clicked a few buttons , There was no reaction at all , But at this point, if you add key Well ?

like this :

  void initState() {
    tiles = [
      StatefulColorfulWidget(key: UniqueKey()),
      StatefulColorfulWidget(key: UniqueKey())
 Copy code 

Then we'll see the effect :


You can see , added key after , It can be exchanged normally again .

Be careful : If you are writing the above code to see the effect , Remember to rerun every time you modify app, Because of our tiles Is defined in initState() Medium ,

Hot reloading does not perform initState() Method , So the effect may not be as expected .

If the whole of the set widget Subtree is stateless , You don't need to key.

Speaking of Statelessness , I think of cool , exactly , This key It's really cool.

Why is that?

In the stateless widget in , Row For his son widget Provides an ordered set of slots .

For each of these widget,Flutter Will build a corresponding Element.

Element tree Save only about each widget The type of , And reference information to child elements ,

We can Element tree As a Flutter The skeleton of the application , It shows the structure of the application , But it can be used to reference the original widget To find all the other information .

When we exchange lines widget The order of ,flutter Can traverse Element Tree To see if the skeleton structure is the same .

From the parent element , That's what we have here Row Start , Then check its child elements ,Element Tree Will check for new widget And the old widget Of runTimeType and key Are they the same? .

If it is , Will update the new widget References to , In the first case , We use StatelessWidget, Because of this widget No, key, therefore flutter Just check its type .

here , We have to StatefulWidget The same analysis is carried out in the case of :

  Save it and upload it directly

Basically the same as before , There is the same Widget Tree and Element Tree, But now there's a couple state object , And the color information is stored here .

Not like it StatelessWidget Stored in Widget In itself .

So now when we exchange 2 individual wdiget The order of ,Flutter Traverse Element Tree, Check widget The type and key, And update references .

Flutter Use Element Tree And its corresponding state to determine the actual displayed content , So it looks like widget Not exchanged correctly .

And when we use key after ,Flutter The inspection will find that key Mismatch , therefore Flutter Meeting deactive these element, And find the connection with this key same element, When found, its pair will be updated widget References to .

here , After the exchange , To the first StatefulTileWidget During the inspection , Find the corresponding... On the right StatefulileElement Of key Mismatch , Will find a match for it element

So is the second , Now it can be replaced normally widget 了 .

Because if you want to modify widget The quantity or order of , that key It's very useful .

Here we use only color as an example , But actually we are state More complex things will be stored in , Like playing animations , Display the data entered by the user , Scroll position, etc , These are all about state .

therefore , Now we have a scene , Need to use key, This key Where should I put it ?

take Key Put it in Widget Where in the tree

We should widget At the top of the tree, specify a to keep key.

As for God, the horse is at the top , Let's look at the reason through the following example :


I'm lazy to use shortcuts for these two StatefulColorfulWidget Added Padding, Then let's look at the effect :

  Station may

It doesn't look like an exchange ? When you click the button ,widget Into random colors , Why just widget use Padding That's what happened after the package ?

( Someone might find out widget The size of the car has changed , That's because of the previous widget Width is 200, added padding Then it's out of screen , I secretly made it smaller )

The following figure shows the added Padding After that Widget Tree and Element Tree The appearance of

image-20200622162128860 When we swap the positions of children ,Flutter Of element To widget The matching algorithm is to view one level of the tree at a time .

At the first level, children , They all match correctly ,

But at the second level ,Flutter Will notice element and widget Of key Mismatch , Therefore, this... Will be disabled element, Remove the association between them ,

Because we use here UniqueKey yes LocalKey, This means that when widget and element When the match ,Flutter Only those that match within a specific level in the tree are found key.

Because the same... Cannot be found at this level key Of element, So a new one will be created , And initialize a new state ,

under these circumstances ,widget There will be a new color .

Of course , Another will have the same problem .

So if we're in Padding add to key Well ?Flutter Will find the right key To reestablish the connection , As in the previous example .

therefore , We now know when to use key, And will be key Where are they .

But if you go Flutter View in the document of key, You will find several different key, So which one should we use ?

Which should I use Key

Key The type of

The first thing we must know is ,key What kind of ?

  • GlobalKey : Throughout APP The only key in
  • LocalKey : In a with the same parent element Elements in , The key must be unique .

GlobalKey There are two uses , It allows the widget stay App Change the parent anywhere without losing state , Or you can use them in Widget Tree Access about another... In a completely different section widget Information about .

For example, to display the same... On two different screens widget, And keep all the same , You can use GlobalKey.

and LocalKey There are the following subclasses :

  • ObjectKey : The key that gets its identity from the object is used as its value .
  • UniqueKey : Only equal to its own Key.
  • ValueKey : Use a specific type of value to identify your own key .
  • PageStorageKey : ValueKey Subclasses of , It defines the PageStorage Where values are saved .

PageStorageKey It is a special device used to store the user's scroll position key, therefore APP You can keep it for later use .

We need to pay attention 3 spot :

1. In a with the same parent element Elements in , The key must be unique . by comparison ,GlobalKeys Must be unique throughout the application .

2.Key The subclass of should be LocalKey or GlobalKey Subclasses of .

3.GlobalKey More expensive , So if it's not necessary , Please use ValueKey, ObjectKey, perhaps UniqueKey.

Use scenarios

In the to-do list application , We may want the text of the to-do to be constant and unique , This situation ,ValueKey Is a good choice , Because its text is value.

If each Widget There are more complex data combinations , Any single field can be the same as another entry , But the combination is the only , You can use ObjectKey.

If there are more than one with the same value in the set widget, Or we want to make sure that everyone widget With other widget Different , You can use UniqueKey.

Our example uses UniqueKey, Because we don't have any other constant data stored on our components , And building widget Before , We don't know what color is yet .


When you want to cross widget When the tree remains in state , You should use key.

When modifying the same type of widget When the collection , To put key Put it where you want to keep it widget The top of the tree .

And according to widget Select the corresponding data type stored in key.

copyright notice
author[__ white],Please bring the original link to reprint, thank you.

Random recommended