Im unsure about wether caching a widget instance and reusing it in the build() method makes a significant difference.
Suppose we have two widget classes:
class ParentWidget extends StatelessWidget {
ParentWidget({Key key})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container( // or some other widgets that define the ui
child: ChildWidget(/*...*/),
);
}
}
class ChildWidget extends StatelessWidget {
ChildWidget({Key key}) : super(key: key); // no constant
@override
Widget build(BuildContext context) {
/*
* returns some Widget
*/
}
}
From my understanding, everytime Flutter calls build() on the ParentWidget, a new ChildWidget is created and attached to the same Element in the element tree. Except if const ChildWidget is available (e.g. ChildWidget has a const constructor).
However, we can cache the child like so:
class ParentWidget extends StatelessWidget {
final Widget child;
ParentWidget({Key key})
: child = ChildWidget(/*...*/),
super(key: key);
@override
Widget build(BuildContext context) {
return Container(
// or some other widgets that define the ui
child: child, // <-- use child instead of ChildWidget()
);
}
}
From my understanding, the same widget will be used and no modification of the element tree has to be done by flutter. But I am unsure in which cases that matters.
Is there a significant difference between caching a widget and creating a new Widget with the same configuration? If so, is there a rule on when to cache widgets instead of reconstructing them?