current position:Home>Brief introduction to fluent key
Brief introduction to fluent key
2021-08-27 08:59:11 【__ white】
This is my participation 8 Yue Gengwen challenges 23 God , Check out the activity details :8 Yuegengwen challenge
Flutter Key
When widget
stay widget tree
When moving in ,key
You can keep its state .
key
Can be used to retain the user's scroll position , Or keep the state when modifying the collection .
When do you need Key
If you haven't used it key
, Explain that you may not need to use key
.
That's exactly what happened , Most of the time , We don't need to use key
.
But if you find yourself needing to add , Delete or reorder the same type of... In a certain state widget
When you gather , Maybe you need to use key
It's time .
Let's start with an official example key
The role of , Exchange two different colors widget
class KeyStudy extends StatefulWidget {
@override
_KeyStudyState createState() => _KeyStudyState();
}
class _KeyStudyState extends State<KeyStudy> {
List<Widget> tiles;
@override
void initState() {
super.initState();
tiles = [StatelessColorfulWidget(), StatelessColorfulWidget()];
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: tiles,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () {
setState(() {
tiles.insert(1, tiles.removeAt(0));
});
}),
);
}
}
class StatelessColorfulWidget extends StatelessWidget {
static List<Color> colorList = [Colors.blue, Colors.yellow, Colors.red];
final defaultColor = colorList[new Random().nextInt(3)];
@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 200,
color: defaultColor,
);
}
}
Copy code
The code is not complicated , We first define a stateless widget
:StatelessColorfulWidget
,
Then place... Side by side on the page 2 It's time widget
.
Switch the two... By clicking the button widget
The location of .
It looks normal , The operation also meets our expectations , At this point we are going to StatelessColorfulWidget
from StatelessWidget
Switch to StatefulWidget
, And store the color in state
in ,
class StatefulColorfulWidget extends StatefulWidget {
StatefulColorfulWidget({Key key}) : super(key: key);
@override
_StatefulColorfulWidgetState createState() => _StatefulColorfulWidgetState();
}
class _StatefulColorfulWidgetState extends State<StatefulColorfulWidget> {
Color defaultColor;
@override
void initState() {
super.initState();
defaultColor = StatelessColorfulWidget.colorList[new Random().nextInt(3)];
}
@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 200,
color: defaultColor,
);
}
}
Copy code
The code is still not complex , And then use StatefulColorfulWidget
replace tiles
Medium StatelessColorfulWidget
, Take a look at the effect :
I clicked a few buttons , There was no reaction at all , But at this point, if you add key Well ?
like this :
@override
void initState() {
super.initState();
tiles = [
StatefulColorfulWidget(key: UniqueKey()),
StatefulColorfulWidget(key: UniqueKey())
];
}
Copy code
Then we'll see the effect :
You can see , added key
after , It can be exchanged normally again .
Be careful : If you are writing the above code to see the effect , Remember to rerun every time you modify app
, Because of our tiles
Is defined in initState()
Medium ,
Hot reloading does not perform initState()
Method , So the effect may not be as expected .
If the whole of the set widget
Subtree is stateless , You don't need to key
.
Speaking of Statelessness , I think of cool
, exactly , This key
It's really cool
.
Why is that?
In the stateless widget
in , Row
For his son widget Provides an ordered set of slots .
For each of these widget
,Flutter Will build a corresponding Element
.
Element tree
Save only about each widget
The type of , And reference information to child elements ,
We can Element tree
As a Flutter The skeleton of the application , It shows the structure of the application , But it can be used to reference the original widget
To find all the other information .
When we exchange lines widget
The order of ,flutter Can traverse Element Tree
To see if the skeleton structure is the same .
From the parent element , That's what we have here Row
Start , Then check its child elements ,Element Tree
Will check for new widget
And the old widget
Of runTimeType
and key
Are they the same? .
If it is , Will update the new widget
References to , In the first case , We use StatelessWidget
, Because of this widget
No, key
, therefore flutter Just check its type .
here , We have to StatefulWidget
The same analysis is carried out in the case of :
Basically the same as before , There is the same Widget Tree
and Element Tree
, But now there's a couple state
object , And the color information is stored here .
Not like it StatelessWidget
Stored in Widget
In itself .
So now when we exchange 2 individual wdiget
The order of ,Flutter Traverse Element Tree
, Check widget
The type and key
, And update references .
Flutter Use Element Tree
And its corresponding state to determine the actual displayed content , So it looks like widget
Not exchanged correctly .
And when we use key
after ,Flutter The inspection will find that key
Mismatch , therefore Flutter Meeting deactive these element, And find the connection with this key
same element
, When found, its pair will be updated widget
References to .
here , After the exchange , To the first StatefulTileWidget
During the inspection , Find the corresponding... On the right StatefulileElement
Of key
Mismatch , Will find a match for it element
So is the second , Now it can be replaced normally widget
了 .
Because if you want to modify widget
The quantity or order of , that key
It's very useful .
Here we use only color as an example , But actually we are state
More complex things will be stored in , Like playing animations , Display the data entered by the user , Scroll position, etc , These are all about state .
therefore , Now we have a scene , Need to use key
, This key
Where should I put it ?
take Key Put it in Widget Where in the tree
We should widget
At the top of the tree, specify a to keep key
.
As for God, the horse is at the top , Let's look at the reason through the following example :
I'm lazy to use shortcuts for these two StatefulColorfulWidget
Added Padding
, Then let's look at the effect :
It doesn't look like an exchange ? When you click the button ,widget
Into random colors , Why just widget
use Padding
That's what happened after the package ?
( Someone might find out widget The size of the car has changed , That's because of the previous widget Width is 200, added padding Then it's out of screen , I secretly made it smaller )
The following figure shows the added Padding
After that Widget Tree
and Element Tree
The appearance of
When we swap the positions of children ,Flutter Of
element
To widget
The matching algorithm is to view one level of the tree at a time .
At the first level, children , They all match correctly ,
But at the second level ,Flutter Will notice element
and widget
Of key
Mismatch , Therefore, this... Will be disabled element
, Remove the association between them ,
Because we use here UniqueKey
yes LocalKey
, This means that when widget
and element
When the match ,Flutter Only those that match within a specific level in the tree are found key
.
Because the same... Cannot be found at this level key
Of element
, So a new one will be created , And initialize a new state ,
under these circumstances ,widget
There will be a new color .
Of course , Another will have the same problem .
So if we're in Padding
add to key
Well ?Flutter Will find the right key
To reestablish the connection , As in the previous example .
therefore , We now know when to use key
, And will be key
Where are they .
But if you go Flutter View in the document of key
, You will find several different key
, So which one should we use ?
Which should I use Key
Key The type of
The first thing we must know is ,key What kind of ?
- GlobalKey : Throughout APP The only key in
- LocalKey : In a with the same parent element Elements in , The key must be unique .
GlobalKey There are two uses , It allows the widget
stay App Change the parent anywhere without losing state , Or you can use them in Widget Tree
Access about another... In a completely different section widget
Information about .
For example, to display the same... On two different screens widget
, And keep all the same , You can use GlobalKey.
and LocalKey
There are the following subclasses :
- ObjectKey : The key that gets its identity from the object is used as its value .
- UniqueKey : Only equal to its own Key.
- ValueKey : Use a specific type of value to identify your own key .
- PageStorageKey : ValueKey Subclasses of , It defines the PageStorage Where values are saved .
PageStorageKey It is a special device used to store the user's scroll position key, therefore APP You can keep it for later use .
We need to pay attention 3 spot :
1. In a with the same parent element Elements in , The key must be unique . by comparison ,GlobalKeys Must be unique throughout the application .
2.Key The subclass of should be LocalKey or GlobalKey Subclasses of .
3.GlobalKey More expensive , So if it's not necessary , Please use ValueKey, ObjectKey, perhaps UniqueKey.
Use scenarios
In the to-do list application , We may want the text of the to-do to be constant and unique , This situation ,ValueKey
Is a good choice , Because its text is value
.
If each Widget
There are more complex data combinations , Any single field can be the same as another entry , But the combination is the only , You can use ObjectKey
.
If there are more than one with the same value in the set widget
, Or we want to make sure that everyone widget
With other widget
Different , You can use UniqueKey
.
Our example uses UniqueKey
, Because we don't have any other constant data stored on our components , And building widget
Before , We don't know what color is yet .
Summary
When you want to cross widget
When the tree remains in state , You should use key
.
When modifying the same type of widget
When the collection , To put key
Put it where you want to keep it widget
The top of the tree .
And according to widget Select the corresponding data type stored in key
.
copyright notice
author[__ white],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827085904254y.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich