【问题标题】:Alert Dialogs: Looking up a deactivated widget's ancestor is unsafe警报对话框:查找已停用小部件的祖先是不安全的
【发布时间】:2021-04-17 17:24:17
【问题描述】:

在下面的代码中,我在提交表单时显示一个带有加载程序的对话框,然后在出现错误时,通过从其上下文中弹出来关闭对话框。但是,Flutter 给了我这个错误,因为弹出后上下文不再可用,但这不会破坏我的应用程序,因为每次显示对话框时我都会重新创建上下文。那么,为了改进我的代码,我可以做些什么来修复这个错误呢?

最终目标:提交时显示loader,如果有错误,停止loader并显示toast

** 我知道还有其他解决方案,例如为脚手架创建全局密钥,但我在这里寻找一个简单的解决方案:)

Widget build(BuildContext context) {
    BuildContext loadingDialogContext;

    return BlocListener<SignUpBloc, SignUpState>(
      listener: (context, state) {
        String message;
        final formStatus = state.formSubmissionStatus;
        if (formStatus is SubmissionFailure) {
          Navigator.of(loadingDialogContext).pop();
          final e = formStatus.exception;
          if (e.code == 'UsernameExistsException' ||
              e.code == 'InvalidParameterException' ||
              e.code == 'InvalidPasswordException' ||
              e.code == 'ResourceNotFoundException') {
            message = e.message;
          } else {
            message = 'An unknown error had occurred. Please try again.';
          }
          toast(
            context: context,
            text: message,
            backgroundColor: kErrorColor,
            textColor: Colors.white,
            iconColor: Colors.white,
          );
        } else if (formStatus is SubmissionInProgress) {
          showDialog(
            context: context,
            builder: (dialogContext) {
              loadingDialogContext = dialogContext;
              return Loader();
            },
            barrierDismissible: false,
          );
        }
      },
      child: Form(
        key: _formKey,
        child: Column(

【问题讨论】:

    标签: android ios flutter dart


    【解决方案1】:

    你可以使用Scaffold.of:

    final scaffoldContext = Scaffold.of(loadingDialogContext).pop();
    Navigator.of(loadingDialogContext).pop();
    toast(
       context: scaffoldContext,
       text: message,
       backgroundColor: kErrorColor,
       textColor: Colors.white,
       iconColor: Colors.white,
    );
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2021-11-15
      • 2021-06-03
      • 2020-12-26
      • 2022-06-26
      • 2021-04-29
      • 2021-07-28
      • 2020-09-18
      • 2022-11-12
      相关资源
      最近更新 更多