当前位置:网站首页>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 .
边栏推荐
- Prism framework
- I/o virtualization technology - vfio
- Kotlin learning apply plugin: 'kotlin Android extensions‘
- Flask入门
- 如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup
- ABP framework Practice Series (III) - domain layer in depth
- ABP framework Practice Series (I) - Introduction to persistence layer
- 【Flink】Flink Sort-Shuffle写流程简析
- English version of ternary loss
- 力扣 515. 在每个树行中找最大值
猜你喜欢
MySQL advanced Chapter 1 (installing MySQL under Linux) [2]
【Flink】Flink Sort-Shuffle写流程简析
[Flink] Flink source code analysis - creation of jobgraph in batch mode
What's wrong with connecting MySQL database with eclipse and then the words in the figure appear
"Renegotiation" agreement
[LOJ 6718] nine suns' weakened version (cyclic convolution, arbitrary modulus NTT)
Nepal graph learning Chapter 3_ Multithreading completes 6000w+ relational data migration
阿里云函数计算服务一键搭建Z-Blog个人博客
如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup
高性能算力中心 — RoCE — Overview
随机推荐
Dynamic segment tree leetcode seven hundred and fifteen
Non H5 end of uni app, regional setting of status bar on the top of mobile phone
2022.6.23-----leetcode. thirty
[LOJ 6718] nine suns' weakened version (cyclic convolution, arbitrary modulus NTT)
Sqlitestudio download address
Uni app custom drop-down selection list
What does virtualization mean? What technologies are included? What is the difference with private cloud?
ABP framework Practice Series (III) - domain layer in depth
"Renegotiation" agreement
QPS的概念和实现
2020 summary: industrial software development under Internet thinking
Uni app, the text implementation expands and retracts the full text
Small record of neural network learning 71 - tensorflow2 deep learning with Google Lab
Quanergy welcomes Lori sundberg as chief human resources officer
阿里云函数计算服务一键搭建Z-Blog个人博客
Go time package: second, millisecond, nanosecond timestamp output
[Flink] Flink batch mode map side data aggregation normalizedkeysorter
【Flink】Flink 批处理模式Map端数据聚合 NormalizedKeySorter
Is the waiting insurance record a waiting insurance evaluation? What is the relationship between the two?
Judge the same value of two sets 𞓜 different values