Keys in Flutter
In Flutter, the Key
is an identifier for StatefulWidget
s and Element
s. It allows Flutter to uniquely identify a Widget
and, in some cases, associate that Widget
with a RenderObject
.
Keys are used in several different situations in Flutter:
- When a
StatefulWidget
is rebuilt, Flutter compares the new widget’skey
to the previous widget’skey
. If the keys are the same, Flutter assumes that the widget is unchanged and will simply reuse the existingElement
to hold the new widget’sstate
. If the keys are different, Flutter will create a newElement
for the new widget. - When the parent of a
StatefulWidget
is rebuilt, Flutter will try to find the child widget in the new tree using the child widget’s key. If it finds the child, it will reuse the existingElement
to hold the child widget’sstate
. If it does not find the child, it will create a newElement
for the child. - When building a
ListView
withListTile
s, it’s important to give eachListTile
a unique key so that Flutter can preserve the state of the tiles when the list is scrolled.
Here is an example of how to use a Key
in Flutter:
class MyWidget extends StatefulWidget {
final String value;
const MyWidget({Key key, this.value}) : super(key: key);
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
// ...
}
In this example, the MyWidget
class has a Key
called key
and a String
called value
. The MyWidget
class is a StatefulWidget
, so it has an associated _MyWidgetState
class that holds its mutable state.
What’s your reaction about this article?
+1
1
+1
1
+1
+1
+1