“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

What is the key

We can see the definition of Key in the source code:

@immutable
abstract class Key {
  const factory Key(String value) = ValueKey<String>;
  @protected
  const Key.empty();
}
Copy the code
  • KeyIs itself an abstract class;
  • You can create one through the factory constructorValueKey;

As can be seen from the definition of ValueKey, value can be of any type.

Key has two direct subclasses: LocalKey and GlobalKey;

  • LocalKeyIs:FlutterIncremental rendering algorithm at the core, throughLocalKeyTo determine theElementWhether to retain or delete; It has several subclasses:
    • ValueKey: takes a value as an argument (number, string);
    • ObjectKey: takes an object as a parameter;
    • UniqueKey: Creates a unique identifier.
  • GlobalKey: Used to help us identify a particular oneWidget,ElementorStateTo access its information; It’s in the whole programThe only;

The use of GlobalKey

Let’s start with a piece of code:

We want to change the number in the Text by clicking the button, which is currently impossible according to the logic of this code, because the button is in the StatelessWidget. If we want to change the value of a Widget, we need to call the setState method in the button click method. StatelessWidget has no setState method;

This would not have been possible in our previous thinking, but GlobalKey would have achieved the same goal;

We have modified the GlobalKeyDemo code as follows:

  • We are inGlobalKeyDemoCreate aGlobalKeyUsed to obtain_ChildPageState(Want to passGlobalKeyPass what you get in the generic. Such as theChildPageTo get directlyChildPage);
  • inChildPageConstructorkeyThe attribute values_globalKey;
  • Because in theChildPageIs called in the constructor ofsuper, so_globalKeyWill andChildPageBinding;

We can obtain this information by using _globalKey:

We modify the code as follows:

The click method of the button is as follows:

FloatingActionButton(
  child: constIcon(Icons.add), onPressed: () { _globalKey.currentState? .setState(() { _globalKey.currentState? .data ='thank you'+ _globalKey.currentState! .count.toString(); _globalKey.currentState? .count ++; }); },),Copy the code

Using _GlobalKey. currentState, you can directly obtain data, count and other attributes for operation.

We can also create multiple GlobalKeys to retrieve different components;

We typically use GlobalKey to manipulate child widgets, although it is possible to pass GlobalKey attributes to other non-child widgets, but it is not recommended.