当我尝试调用对话框时,它会向我显示此错误 setState() 或 markNeedsBuild 在构建期间调用

when i tried to calling a dialog it will show me this error setState() or markNeedsBuild called during build

这是我的对话代码

这是在构建过程中调用 setstate() 或 MarkerneedsBuild 时出现错误。无法将此覆盖小部件标记为需要处理构建小部件。

当我尝试调用 _onAlertOtp 小部件时,它会向我显示此 error.in 构建方法,当我的注册成功时,我会进行分组和说明,然后我必须调用警报对话框。但是当我尝试这样做时,它会向我显示错误。希望你理解这个问题,请帮助我。

  _onAlertotp(BuildContext context) {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Enter OTP'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Container(
                  height: MediaQuery.of(context).size.height / 2.7,
                  width: MediaQuery.of(context).size.width,
                  alignment: Alignment.center,
                  child: ListView(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: Text(
                          'We have Texted and/or Emailed OTP (One Time Pin) to your registered cell phone and/ or email account. Please check and enter OTP below to activate your TUDO account.',
                          style: TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 15),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(
                            vertical: 8.0, horizontal: 30),
                        child: PinCodeTextField(
                          length: 6, // must be greater than 0
                          obsecureText: false, //optional, default is false
                          shape: PinCodeFieldShape
                              .underline, //optional, default is underline
                          onDone: (String value) {
                            setState(() {
                              passcode = value;
                              print(value);
                            });
                          },

                          textStyle: TextStyle(
                              fontWeight: FontWeight
                                  .bold), //optinal, default is TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)
                          onErrorCheck: (bool value) {
                            setState(() {
                              hasError = value;
                            });
                          },
                          shouldTriggerFucntions:
                              changeNotifier.stream.asBroadcastStream(),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 30.0),
                        child: Text(
                          hasError
                              ? "*Please fill up all the cells and press VERIFY again"
                              : "",
                          style: TextStyle(
                              color: Colors.red.shade300, fontSize: 12),
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(
                            text: "Didn't receive the code? ",
                            style:
                                TextStyle(color: Colors.black54, fontSize: 15),
                            children: [
                              TextSpan(
                                  text: " RESEND",
                                  // recognizer: onTapRecognizer,
                                  style: TextStyle(
                                      color: colorStyles["primary"],
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16))
                            ]),
                      ),
                      SizedBox(
                        height: 7,
                      ),
                      Container(
                        margin: const EdgeInsets.symmetric(
                            vertical: 16.0, horizontal: 30),
                        child: ButtonTheme(
                          height: 50,
                          child: FlatButton(
                            onPressed: () async {
                              /// check the [_onData] fucntion to understand better
                              changeNotifier.add(Functions.submit);
                              // at first we will check error on the press of the button.
                              if (!hasError) {
                                _onAlertrunnigbusiness(context);
                              }
                            },
                            child: Center(
                                child: Text(
                              "VERIFY".toUpperCase(),
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            )),
                          ),
                        ),
                        decoration: BoxDecoration(
                          color: colorStyles["primary"],
                          borderRadius: BorderRadius.circular(5),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('Regret'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

这是另一个对话。在第一个对话框中打开验证按钮单击

  _onAlertrunnigbusiness(context) {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Are you running Business?'),
          content: Container(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Text(
                    "TUDO.App aims at Businesses bridging gaps between Business Service Providers and Consumers collaborate on unique technology platform. If you own a business, we strongly recommend, provide your business information to grow your customer base and expand your business services. Any questions? Call us @1-800-888-TUDO"),
                SizedBox(
                  height: 10,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    FlatButton.icon(
                      icon: Icon(FontAwesomeIcons.arrowCircleRight),
                      label: Text('No'),
                      color: colorStyles["primary"],
                      textColor: Colors.white,
                      padding:
                          EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(7),
                      ),
                      onPressed: () {
                        NavigationHelper.navigatetoMainscreen(context);
                      },
                    ),
                    SizedBox(height: 10),
                    FlatButton.icon(
                      icon: Icon(FontAwesomeIcons.arrowCircleRight),
                      label: Text('Yes'),
                      color: colorStyles["primary"],
                      textColor: Colors.white,
                      padding:
                          EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(7),
                      ),
                      onPressed: () {
                        NavigationHelper.navigatetoBspsignupcreen(context);
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

我在这里调用我的对话框

  @override
  Widget build(BuildContext context) {
    return BlocListener<SignupBloc, SignupState>(
      bloc: widget._signupBloc,
      listener: (
        BuildContext context,
        SignupState currentState,
      ) {


        if (currentState is InSignupState) {
          _countries = currentState.countries.countries;
          return Container(child: content(_signupBloc, context, _countries));
        }

        if (currentState is SignupButtonClickedEvent) {
          print('SignupButtonClickedEvent clicked');
          return Container();
        }

        if (currentState is SignupSuccessState) {
          print(
              ' You are awesome. you have successfully registered without confirmation');
          print(currentState.signupUser.toJson());
          print("Hey Otp Is opned");

          if (!_isError) {
            return _onAlertotp(context);
          }
          // NavigationHelper.navigatetoMainscreen(context);
          _isLoading = false;
          showAlertBox = true;
          return Container(
            child: content(_signupBloc, context, _countries),
          );
        }

        if (currentState is SignupVerficationOtp) {
          print('signup verficitaion otp button clicked');
          return Container();
        }
        return Container(child: content(_signupBloc, context, _countries));
      },
    );
  }
}

您应该在构建方法的根部使用 BlocListener 来处理不属于 return 小部件(在您的情况下为 showDialog 方法)的事件

您的 if (currentState is SignupSuccessState) { 部分将在 BlocListener 中而不是在 BlocBuilder 中

尝试使用以下代码显示警告对话框

代替 return _onAlertotp(context);

WidgetsBinding.instance.addPostFrameCallback((_) {
  // show alert dialog here
  _onAlertotp(context);
});