当前位置:网站首页>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 .
边栏推荐
- 【掘金运营套路揭露】真心被掘金的套路....
- Pay attention to the entrance components of official account in the applet
- Matplotlib line chart, text display, win10
- Uni app custom selection date 1 (September 16, 2021)
- Introduction Guide to the flutterplugin plug-in in the actual combat of flutter
- 力扣 515. 在每个树行中找最大值
- Ten important basic principles of software debugging and testing
- 如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup
- Matplotlib multi line chart, dot scatter chart
- matplotlib多条折线图,点散图
猜你喜欢

Open Camera异常分析(一)

使用SOAPUI访问对应的esb工程

Uni app custom navigation bar component

What's wrong with connecting MySQL database with eclipse and then the words in the figure appear

Judge the same value of two sets 𞓜 different values

YOLOv5改进:更换骨干网(Backbone)

Nepal graph learning Chapter 3_ Multithreading completes 6000w+ relational data migration

Yolov5 improvements: replace the backbone

Slide the menu of uni app custom components left and right and click switch to select and display in the middle

2021 year end summary
随机推荐
R language and machine learning
2020 summary: industrial software development under Internet thinking
I/o virtualization technology - vfio
Can string be changed?
Open Camera异常分析(一)
[Flink] Flink source code analysis - creation of jobgraph in batch mode
An error occurred using the connection to database 'on server' 10.28.253.2‘
【掘金运营套路揭露】真心被掘金的套路....
What's wrong with connecting MySQL database with eclipse and then the words in the figure appear
chrome页面录制,重放功能
Unity移动端游戏性能优化简谱之 以引擎模块为划分的CPU耗时调优
matplotlib多条折线图,点散图
Contains an object field at offset position
DETR3D 多2d图片3D检测框架
Use soapUI to access the corresponding ESB project
如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup
ASP. Net startup and running mechanism
[Flink] a brief analysis of the writing process of Flink sort shuffle
WebRTC系列-网络传输之6-Connections裁剪
Ten important basic principles of software debugging and testing