From d2c47acdaa3e30e43087018f24e97ad4b182229c Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Tue, 29 Sep 2020 08:40:26 -0700 Subject: [PATCH] GlobalKey docs improvement (#66834) Improve GlobalKey docs by mentioning a pitfall that some users had where the instantiated it in the build method. --- packages/flutter/lib/src/widgets/framework.dart | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index c41bf68415..00ca2eb92a 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -116,6 +116,20 @@ class ObjectKey extends LocalKey { /// 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