当前位置:网站首页>Detailed explanation of globalkey of flutter

Detailed explanation of globalkey of flutter

2022-06-26 03:57:00 Guowuyou

Before you start reading this article , I hope readers can read the blogger's Flutter And BuilderContext and Widget Relationship analysis and Fultter And Element and Widget Corresponding relation These two blog posts , This is the theoretical knowledge reserve of this blog post . Through these two blog posts, you can learn :
1、Widget and Element Correspondence of
2、Widget and Element Initialization time of
3、Flutter Of BuildContext What the hell is it
4、StatefulWidget Of state Follow StatefulElement The connection between

The code involved in this article demo, Click here to view the

GlobalKey The role of

Say first conclusion , The origin of this conclusion will be analyzed later : Every Widget They all correspond to one Element, We can go straight to Widget To operate , But you can't operate directly Widget Corresponding Element. and GlobalKey That's the direct access Element Key . adopt GlobalKey Can be obtained Widget Corresponding Element, Like getting StatelessElement and StatefulElement. For example, if you get StatefullElement, Then we can get StatefulElement Of State object .
So let's do that Form Form as an example to analyze GlobalKey Why can I get Widget Corresponding Element.

GlobalKey Practical examples

Login must have an input box for entering user name and password , stay Flutter We only use Form Forms +TextFormField In the form of . Now let's talk about Form and TextFormField Simple use ,demo The login interface is as follows :
 Insert picture description here
Then we click... Without entering any characters submit Button , The effect is as follows :
 Insert picture description here
The code of the above layout is as follows :
 Insert picture description here
As shown above, first initialize GlobalKey object . Then set this object to Form Of key, Finally, click Submit Button time , We don't operate directly TextFormField, But through _formKey.currentState.validate To the input box TextFormField Non null validation of the content of . In code _formKey.currentState The type is FormState

 class Form extends StatefulWidget {
    
  const Form({
    
    Key key,
    @required this.child,
   
  }) ;
  
  @override
  FormState createState() => FormState();

 // call Form.of(context) Also available FormState object 
 // Details please see 【Flutter The actual combat InheritedWidget Detailed explanation 】
  static FormState of(BuildContext context) {
    
    final _FormScope scope = context.inheritFromWidgetOfExactType(_FormScope);
    return scope?._formState;
  }

}

GlobalKey obtain Element Principle

 
 abstract class GlobalKey<T extends State<StatefulWidget>> extends Key {
    
  // A static variable map aggregate 
  static final Map<GlobalKey, Element> _registry = <GlobalKey, Element>{
    };
}

, from GlobalKey<T extends State<StatefulWidget>> The class structure of can be seen ,GlobalKey It is mainly used to store status information State<StatefulWidget>,State refer to StatefulWidget State class of , adopt StatefulWidget Of createState Method creation :

abstract class StatefulWidget extends Widget {
    
  //Key It's a options Of , It can be set or not 
  const StatefulWidget({
     Key key }) : super(key: key);
  @protected
  State createState();
}

Why did you pass GlobalKey.currentState I can get it FormState Well ? How are the two related ? Now let's find out .

First look at it. GlobalKey Of currentState The concrete implementation of the method :

  T get currentState {
    
    // Current Element object 
    final Element element = _currentElement;
    // Check if it is SatefulElement object 
    if (element is StatefulElement) {
    
      final StatefulElement statefulElement = element;
      // obtain StatefulElement Object's State object 
      final State state = statefulElement.state;
      // If the status matches , Returns the corresponding T
      if (state is T)
        return state;
    }
    return null;
  }
  //_currentElement It's a map aggregate Map<GlobalKey, Element> 
  // The collection is in GlobalKeyweight object , Its value is saved as Element.
  Element get _currentElement => _registry[this];
   

stay GlobalKey There is a static... Inside _registry Map aggregate , The collection is in GlobalKey by key, With Element by value; It provides currentState The way is to GlobalKey The object is Key Get the corresponding StatefulElement object , And then from StatefulElement.state Get specific values in FormState, So when do you go to _registry Fill the set with data ? adopt Fultter And Element and Widget Correspondence analysis We know one Element After creation, it calls mount Method :

   
  void mount(Element parent, dynamic newSlot) {
    
    /// Omitted code 
    if (widget.key is GlobalKey) {
    
      final GlobalKey key = widget.key;
      // take Element Object registration 
      key._register(this);
    }
   
  }
  //GlobalKey Of _register Method .
  void _register(Element element) {
    
    _registry[this] = element;
  }

It can be found in mount Method will create the Element Injection into GlobalKey Static map Go to the assembly ! therefore GlobalKey Is that :* Hold current Widget Of Element object , So by GlobalKey Object can get the current StatefulWidget Of StatefullElement, Through StatefullElement obtain State State object , To manipulate State Related methods . such as FormState Of validate() Method for non null verification .

In fact, we can also use Form.of(context) The method can also be obtained FormState object , And then call validate Method to complete TextFormField Non empty verification of , The principle is , For detailed analysis, see Flutter The actual combat InheritedWidget Detailed explanation

This blog post was updated on 2021 year 12 month 7 Number .

原网站

版权声明
本文为[Guowuyou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180545203185.html