Widgets & Key property - ArtemMikhaylov/my_flutter_notes GitHub Wiki

How Stateful Widgets Are Used Best - Flutter Widgets 101 Ep. 2 Digest:

Widgets is a blueprint for Elements, if State of StatefullWidget changes (e.g. setState method was called), then it marks Element as dirty, and on the next frame of the Graphic interface, StatefullWidget rebuilds its children (e.g. Widget build(BuildContext context) method will be called).

If a Widget in widgets tree is the same type as the old one, the Element (either Stateless or Stateful) stays right where it is, e.g. it is not recreating but just updates itself with new Widget.

If a StatefullWidget rebuilds itself (e.g. setState was called in State of some parent StatefullWidget), then if the widget is the same type in widgets tree, the State object won't be recreated too.

There is didUpdateWidget(MyHomePage oldWidget) method in the State object, which you can override if you want to know if its Widget was recreated.

For example, as I understand, AnimatedContainer uses this method to animate itself from one config to another with animation (from old widget representation to new), without this element would update itself immediately from old values to new ones.


For example with changing colors of two squares, stateless squares work like expected, because while elements aren't recreating, they update themselves with new widgets with new color values. When we change example by making squares stateful, it stops working, because not only elements stay the same, but their states as well, which preserve color values. But if we provide squares with keys, then all work again. Cause this time since keys are different, the elements with their state objects will be actually rechanged.

When we wrap our squares with Padding widgets, squares won't be exchanged, but new ones will be created, because it is local keys, and Flutter searches for rechange in the level of a tree this widget belongs. Flutter doesn't find the Element with the same key as in the new Widget, so Flutter creates a new one with a new State.

Key types:

  • ValueKey
  • ObjectKey
  • UniqueKey
  • PageStorageKey
  • GlobalKey - allow Widgets to change parents anywhere in your app without losing state. Or they can be used to access information about another widget in a completely different part of the widget tree.

"If the new widget you switching in is the same type as the previous widget. Don't forget to set the 'key' property, to get that animation."


If you want to use keys in your widget, don't forget to pass them to super constructor

class MyWidget extends StatefulWidget {

  MyWidget({Key key}) : super(key: key);

  @override
  _MyWidgetState createState() => _MyWidgetState();
}