Flutter-弹出导航器时运行StreamBuilder构建器功能 [英] Flutter - StreamBuilder builder function runs when navigator pops

查看:181
本文介绍了Flutter-弹出导航器时运行StreamBuilder构建器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为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!

  1. 我认为可能会发生,因为正在重建RootContainer,但是在StreamBuilder之前放置print只能打印一张.

  1. I thought it may happen because the RootContainer is being rebuilt, but placing a print before the StreamBuilder 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆