GlobalKey<T extends State<StatefulWidget>> class abstract

A key that is unique across the entire app.

Global keys uniquely identify elements. Global keys provide access to other objects that are associated with those elements, such as BuildContext. For StatefulWidgets, global keys also provide access to State.

Widgets that have global keys reparent their subtrees when they are moved from one location in the tree to another location in the tree. In order to reparent its subtree, a widget must arrive at its new location in the tree in the same animation frame in which it was removed from its old location in the tree.

Reparenting an Element using a global key is relatively expensive, as this operation will trigger a call to State.deactivate on the associated State and all of its descendants; then force all widgets that depends on an InheritedWidget to rebuild.

If you don't need any of the features listed above, consider using a Key, ValueKey, ObjectKey, or UniqueKey instead.

You cannot simultaneously include two widgets in the tree with the same global key. Attempting to do so will assert at runtime.

Pitfalls

GlobalKeys should not be re-created on every build. They should usually be long-lived objects owned by a State object, for example.

Creating a new GlobalKey on every build will throw away the state of the subtree associated with the old key and create a new fresh subtree for the new key. Besides harming performance, this can also cause unexpected behavior in widgets in the subtree. For example, a GestureDetector in the subtree will be unable to track ongoing gestures since it will be recreated on each build.

Instead, a good practice is to let a State object own the GlobalKey, and instantiate it outside the build method, such as in State.initState.

See also:

  • The discussion at Widget.key for more information about how widgets use keys.
Inheritance
Implementers
Annotations

Constructors

GlobalKey({String? debugLabel})
Creates a LabeledGlobalKey, which is a GlobalKey with a label used for debugging.
factory
GlobalKey.constructor()
Creates a global key without a label.
const

Properties

currentContext BuildContext?
The build context in which the widget with this key builds.
no setter
currentState → T?
The State for the widget in the tree that currently has this global key.
no setter
currentWidget Widget?
The widget in the tree that currently has this global key.
no setter
hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited