I've been searching around and didn't quite find a suitable answer to this question: is it ok to reuse a widget in a subsequent build call? By that I mean that I create a StatefulWidget
and in the build function I keep an internal reference to the returned widget. On later build (if I determine that nothing has changed since last build), I then return the last widget instead of building a new one.
I understand that one should avoid that, create simple builds and optimise invalidation process so that complex widgets don't get rebuilt too often. But under some circumstances, I find this can be a good solution.
Reading on this official doc page in particular, it is stated:
The traversal to rebuild all descendents stops when the same instance of the child widget as the previous frame is re-encountered. This technique is heavily used inside the framework for optimizing animations where the animation doesn’t affect the child subtree. See the TransitionBuilder pattern and the source code for SlideTransition, which uses this principle to avoid rebuilding its descendents when animating.
So doing something like this should be acceptable:
abstract class SmartState<T extends StatefulWidget> extends State<T> {
Widget _lastBuild;
T _previousWidget;
bool shouldRebuild(T previousWidget);
Widget doBuild(BuildContext context);
@override
@mustCallSuper
Widget build(BuildContext context) {
final T previousWidget = _previousWidget;
_previousWidget = widget;
if (previousWidget != null && _lastBuild != null && !shouldRebuild(previousWidget)) {
return _lastBuild;
}
_lastBuild = doBuild(context);
return _lastBuild;
}
}
As a little background, I intend to extend this class in a list item. The list itself changes at times and is rebuilt with the new items, although most of the items remain the same, I just rearrange them, remove or add some. Also note that I had to put them in a Wrap
widget because of design requirements.
So does anyone has any counter-indication or better solution than this. And most of all, I would like to know if it is considered ok or good practice to do such a reuse. Thanks!