Aquarius_Girl
Aquarius_Girl

Reputation: 22926

Why does a Form need a GlobalKey in Flutter?

https://flutter.dev/docs/cookbook/forms/validation

They have used a GlobalKey in that Form.

From here: https://api.flutter.dev/flutter/widgets/GlobalKey-class.html

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.

Which feature from above quote is being used in that Form such that it requires a GlobalKey?
Why is the GlobalKey required there and why wouldn't any other key work?

Upvotes: 7

Views: 3256

Answers (1)

petchgabriel
petchgabriel

Reputation: 198

I think the important feature that are using on GlobalKey is formKey.currentState.validate() method for validating all of TextFormField widgets in that Form. Because of GlobalKey can access to current state of the FormState.

In other key type such as ValueKey cannot access to the current state of FormState.

Upvotes: 6

Related Questions