1

我有一个问题,当我尝试将 navigator pop() 方法放入字符串生成器时,会出现此错误:setState() or markNeedsBuild() called during build.

我读到您不能在流构建器中调用导航器,所以有人对如何解决这个问题有任何想法吗?

这是我的代码:

return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: Center(
        child: Container(
            padding: EdgeInsets.all(15),
            color: Colors.white,
            child: Column(
              children: <Widget>[
                SizedBox(height: 55),
                SvgPicture.asset('images/svg_example.svg'),
                SizedBox(height: 55),
                Text("Login App",
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.black)),
                SizedBox(height: 40),
                emailField,
                SizedBox(height: 45),
                passwordField,
                SizedBox(height: 45),
                loginButton,
                SizedBox(height: 15),
                StreamBuilder<ApiResponse<LoginResponse>>(
                  stream: userBloc.authenticationUserStream,
                  builder: (context,
                      AsyncSnapshot<ApiResponse<LoginResponse>> snapshot) {
                    // it will observe changes on the ApiResponse<LoginResponse>
                    if (!snapshot.hasData) return Container();
                    switch (snapshot.data.status) {
                      case Status.LOADING:
                        return Loading(
                          loadingMessage: "loading",
                        );
                      case Status.COMPLETED:
                        prefs.saveTokenPref(snapshot.data.data.token);
                        prefs.saveUserPref(snapshot.data.data.user);
                        goToMain();
                        return Container(width: 0.0, height: 0.0);
                      case Status.ERROR:
                        // Here you can go to another screen after login success.
                        return Center(
                          child: Text("${snapshot.data.message}"),
                        );
                      default:
                        return Container();
                    }
                  },
                )
              ],
            )),
      ),
    );
  }

  goToMain() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => MainScreen()),
    );
  }
4

1 回答 1

1

好的,所以考虑到我的问题是-1,因为有人只是想在没有真正帮助帖子的情况下给予,我在这里给出了这个问题的答案:

您只需要在您的initState() This 上执行此操作即可侦听流本身并在 Stream Builder 之外创建 UI 逻辑。

@override
  void initState() {
    userBloc = UserBloc();

    super.initState();
    userBloc.userSubject.listen((state) {
      if (state.status == Status.COMPLETED) {
        goToMain();
      }
    });
  }
于 2019-11-19T02:02:32.267 回答