The child widget of the ListenableBuilder is rebuilt even though it claims to preserve the child widget from re-building.
In the example below counterNotifier is an instance of ChangeNotifier. I believe there is no need to see its implementation, I'm simply calling notifyListener() when changes are done.
ListenableBuilder(
listenable: counterNotifier,
builder: (context, child) {
if (counterNotifier.isLoading) {
return const AppLoader();
}
if (counterNotifier.value == null) {
return const SizedBox.shrink();
}
return Row(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
child!,
Text('${counterNotifier.value}'),
],
);
},
child: const CountText(),
),
Issue
The reason why the child is rebuilt is that I was returning the widget conditionally in the builder callback.
This changes the widget tree as per the condition, hence the
childwas not preserved in the widget tree.Fix
To fix this, we can use
Offstagewhich hides the widget from view but the widget is still present in the widget tree.Example
After changes the
ListenableBuilderwill look like this:Note
Instead of
Stack, you can use whatever best suits you.