Flutter:ListenableBuilder 正在重建子部件

问题描述 投票:0回答:1

ListenableBuilderchild 小部件被重建,即使它声称保留子小部件不被重建。

在下面的示例中,

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(), ),
    
flutter dart listener flutter-change-notifier changenotifier
1个回答
0
投票
问题

重建子级的原因是我在构建器回调中

有条件地返回小部件。

这会根据条件更改小部件树,因此

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

,您可以使用最适合您的任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.