ListenableBuilder 的 child 小部件被重建,即使它声称保留子小部件不被重建。
在下面的示例中,counterNotifier
是
ChangeNotifier
的实例。我相信没有必要查看它的实现,我只是在更改完成后调用
notifyListener()
。
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(),
),
有条件地返回小部件。
这会根据条件更改小部件树,因此child
未保留在小部件树中。
Offstage
隐藏小部件,但该小部件仍然存在于小部件树中。
ListenableBuilder
将如下所示:
return ListenableBuilder(
listenable: listenable,
builder: (context, child) {
final isLoading = listenable.isLoading;
final hasData = listenable.value != null;
return Stack(
children: [
Offstage(
offstage: !isLoading,
child: const AppLoader(),
),
Offstage( // <-- This one is unnecessary in this case. This is just for the sake of converting the code.
offstage: !hasData,
child: const SizedBox.shrink(),
),
Offstage(
offstage: isLoading || !hasData,
child: builder(context, listenable.value!, child),
),
],
);
},
child: child,
);
Stack
,您可以使用最适合您的任何内容。