当前位置:网站首页>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 Detailed explanation
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 :
Then we click... Without entering any characters submit Button , The effect is as follows :
The code of the above layout is as follows :
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 .
边栏推荐
猜你喜欢

(15) Blender source code analysis flash window display menu function

【LOJ#6718】九个太阳「弱」化版(循环卷积,任意模数NTT)
![[Flink] Flink source code analysis - creation of jobgraph in batch mode](/img/8e/1190eec23169a4d2a06e1b03154d4f.jpg)
[Flink] Flink source code analysis - creation of jobgraph in batch mode

1. foundation closing

Matplotlib multi line chart, dot scatter chart

EF core Basics

Uni app, the text implementation expands and retracts the full text

Analysis of camera memory memory leakage (II)

High performance computing center roce overview

阿里云函数计算服务一键搭建Z-Blog个人博客
随机推荐
【掘金运营套路揭露】真心被掘金的套路....
WPF 值转换
Slide the menu of uni app custom components left and right and click switch to select and display in the middle
JS to achieve the effect of text marquee
Intelligent manufacturing learning videos and books
【好书集锦】从技术到产品
763. dividing alphabetic intervals
2022.6.25-----leetcode. Sword finger offer 091
Uni app custom drop-down selection list
Uni app swiper rotation chart (full screen / card)
Quanergy welcomes Lori sundberg as chief human resources officer
Camera-CreateCaptureSession
What preparations should be made to develop an app from scratch
2020 summary: industrial software development under Internet thinking
MySQL common statements
Non H5 end of uni app, regional setting of status bar on the top of mobile phone
go time包:秒、毫秒、纳秒时间戳输出
商城风格也可以很多变,DIY 了解一下
2022.6.20-----leetcode. seven hundred and fifteen
Prism framework project application - Navigation