The principle and use of Flutter Key (1) What happens without Key

The principle and use of Flutter Key (1) What happens without Key

The principle and use of Flutter Key (2) Correspondence between Widget and Element

The principle and use of Flutter Key (3) Three types of LocalKey

Principle and use of Flutter Key (4) Usage of GlobalKey

The principle and use of Flutter Key (5) An example that requires a key: a Listview that can be dragged to change the order

In flutter, almost every widget has a Key, but we generally don’t pass the Key when we use it, so what is this Key for? Almost every widget has it, but we rarely use it It. When is it necessary to use it?

Next, let's take a look at what happens if the key is not used when the key is needed.

Let me give you a common example:

Column(
  children: [
    Container(width: 100, height: 100,color: Colors.red),
    Container(width: 100, height: 100,color: Colors.blue),
  ]
),

If there is the above piece of code, then two squares will be displayed, as shown in the figure:

image.png

If you Containerswitch the two positions, the two squares will also change positions on the UI. This is nothing to say, it is easy to understand.
What about two slightly more complicated widgets?

Now create a new Widiget:

class Box extends StatefulWidget {
  final Color color;

  const Box(this.color, {Key? key}) : super(key: key);

  @override
  _BoxState createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 100,
        height: 100,
        color: widget.color,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('$count', style: TextStyle(color: Colors.white)),
            IconButton(
              onPressed: () {
                setState(() {
                  count++;
                });
              },
              icon: Icon(Icons.add),
            )
          ],
        ));
  }
}

This Widget contains one internally count, manages its state by itself, and has a method to change this value.
The code is as follows:

Column(
  children: [
    Box(Colors.red),
    Box(Colors.blue),
  ],
)

Now replace the above with this Widget Container, and change their values ​​respectively:

Then we swap the positions of the two widgets to see the effect afterwards:

1212.gif

It can be seen that although its color has been changed, the numbers have not been exchanged, which does not seem to be the effect we expected.

Let's try changing the code again

Column(
  children: [
    Box(Colors.red),
    Box(Colors.blue),
    Box(Colors.red),
  ],
)

image.png

Then we remove the first box, which is the red widget, and hotreload it, what will it look like?

12123.gif

It's amazing, the red one has indeed disappeared, but logically it should be removed first, while the blue 2 and red 3 remain, but the first two remain, and the values ​​are still the first and the second.

It seems that Flutter can't tell who is who, but in our opinion, there is no complicated logic here.

So what if we change to 3 red boxes?
Change the code to this:

Column(
  children: [
    Box(Colors.red),
    Box(Colors.red),
    Box(Colors.red),
  ],
)

Then we delete the first one, the code becomes:

Column(
  children: [
    Box(Colors.red),
    Box(Colors.red),
  ],
)

If I didn't delete it myself, I don't know which one is missing. I only know that one is missing.

What if we still change the order as before? The UI has not changed, but the code has not changed after the switch, so it seems that the UI has not changed and it is not surprising. The code has not changed, what do you expect the UI to change?

It seems that I have found a little inspiration. Does it mean that Flutterthe color cannot be used to identify which one is widget, or that the color cannot be used as the only identification of the widget. At this time, we need one to uuiddistinguish the different ones widget, and this is keythe function of the widget.

If we pass in different keys to the widgets, it is equivalent to having an id for each. If the three ids are different, flutter will not confuse them.

Flutter has several different keys, which I will introduce to you later.
When defining the box component before, a parameter has been defined key. At this time, we pass in different keys respectively.

Box(Colors.red,key: ValueKey(1)),
Box(Colors.red,key: ValueKey(2)),
Box(Colors.red,key: ValueKey(3)),

Because of the key, flutter can distinguish them. Now whether we replace or delete them widget, the changes of flutter will develop in the direction we expected.

In actual development, we will also encounter the problem of confusion between different widgets. In general, adding one ValueKeycan solve it.

As for the situation that ValueKeycannot be resolved, we will introduce it later.

Guess you like

Origin blog.csdn.net/u011272795/article/details/120034166