Flutter-弹出导航器时运行StreamBuilder构建器功能 [英] Flutter - StreamBuilder builder function runs when navigator pops
问题描述
我有一个名为RootContainer
的小部件,该小部件接收Widget child
并将其包装在StreamBuilder
中:
I have a widget called RootContainer
which receives a Widget child
and wrap it inside a StreamBuilder
:
class RootContainer extends StatelessWidget {
final Widget child;
RootContainer({this.child});
@override
Widget build(BuildContext context) {
return StreamBuilder<OverlayAlert>(
stream: ApiService.ThrottledException.stream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
Future.delayed(Duration.zero, () => showAlert(context, snapshot));
}
return this.child;
},
);
}
void showAlert(BuildContext context, snapshot) {
print("showing dialog");
showDialog(
context: context,
builder: (context) => OverlayAlertDialog(snapshot),
);
}
发生错误时,我向流ApiService.exception.stream
添加一个新值,该值将触发StreamBuilder构建器,然后打开一个对话框.
When an error occurs, I add a new value to the stream ApiService.exception.stream
which triggers the StreamBuilder builder and then it opens a dialog.
这是当前的小部件树:
当我想弹出导航器时,问题就开始了,StreamBuilder.builder
又重新构建了!
The problem starts when I want to pop the navigator, the StreamBuilder.builder
builds again!
-
我认为可能会发生,因为正在重建
RootContainer
,但是在StreamBuilder
之前放置print
只能打印一张.
I thought it may happen because the
RootContainer
is being rebuilt, but placing aprint
before theStreamBuilder
has resulted in just one print.
我尝试.listen
到流,并且当我弹出导航器时流没有触发,因此我可以确认ApiService.ThrottledException.stream
没问题.
I tried to .listen
to the stream, and the stream didn't fire when I popped the navigator so I can confirm that there's nothing wrong with ApiService.ThrottledException.stream
.
弹出导航器时的快照(数据)等于上一次发射的快照.
The snapshot when the navigator is popped is equal (the data) to the last emission.
您可以在以下演示中看到,每当我按下后退"按钮时,对话框都会再次弹出:
You can see in the following demo that whenever I press the back button the dialog pops up again:
当我按下后退"按钮时,什么会导致StreamBuilder
自身重建?
What could cause the StreamBuilder
to rebuild itself when I press on the back button?
推荐答案
我不得不更改RootContainer
以扩展StatefulWidget
而不是StatelessWidget
.
I had to change RootContainer
to extend StatefulWidget
instead of StatelessWidget
.
我不知道幕后发生了什么,但是它起作用了!任何解释都很好.
I have no idea what's happening behind the scene, but it works! Any explanation would be nice.
这篇关于Flutter-弹出导航器时运行StreamBuilder构建器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!