Reputation: 631
I'm trying to better understand what is happening in the
official example
for AnimatedPositioned
.
From this
article
(and accompanying video)
we know that even if the widget object itself remains the same, but just changes position
in the widget tree, then we have to include a key if the widget is a StatefulWidget
.
Well, in the
official example
for AnimatedPositioned
, there is no key used.
When selected
is flipped, setState
triggers a second call for the build()
method.
Not only does this second call not just reposition the exact same StatelessWidget
,
it also creates an entirely new AnimatedPositioned
object.
How does Flutter know that this widget is the same widget as before (to animate it properly)? Is it just the position in the widget tree? But we could have multiple widgets, and this is a StatefulWidget
.
Why is a key sometimes not needed for a StatefulWidget?
Upvotes: 0
Views: 751
Reputation: 24671
The reason keys aren't always used in a StatefulWidget
is because keys are good at two things*: maintaining the correct state when a widget changes position in the widget tree, and being able to directly query a specific widget when performing tests.
In the official example for AnimatedPositioned
, a key is redundant because there is no mechanism in that example that would cause the widget to become repositioned in the widget tree, so the state is in no danger of becoming lost or misassigned. And since this example isn't concerned with showing how the widget can be referenced in a testing context, that use case is also irrelevant.
In theory, you should assign unique keys for your StatefulWidget
s in order to guarantee safety from Flutter's inner workings. In practice, though, assigning a unique key for every single widget in the entire app is overkill, and you should only really use keys when there's a reason to do so. Otherwise it becomes one of those practices that can involve a lot of sunk time and boilerplate for little to no real benefit.
*: Keys can also be used diagnostically when using the DevTools to view your app's widget tree. They can also be used to traverse the widget tree when looking for a specific widget, but this use is discouraged as you should use state management tools if you need to get information from one widget to another.
Upvotes: 1