You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中输入正确密码后无法从showDialog跳转至下一页面

问题原因与解决方案

核心问题

你的代码存在两个关键问题导致页面跳转失效:

  1. 重复执行pop():TextButton的onPressed回调末尾,无论密码是否正确都会执行Navigator.of(context).pop();。密码正确时,你先关闭对话框(第一次pop),然后触发跳转,但紧接着的第二次pop会干扰导航栈,直接打断跳转操作。
  2. context作用域混淆:showDialog的builder函数内的context属于对话框的上下文,用它执行push无法正确访问页面的导航栈。

修复后的代码

return Expanded(
  child: ListView.builder(
      padding: EdgeInsets.zero,
      itemCount: provider.count_notes,
      itemBuilder: (context, index) {
        // 提前获取外层页面的context,避免对话框context干扰
        final pageContext = context;
        final note = provider.getAllNotes[index];
        return NoteWidget(
          onTap: () {
            if(note.isLocked==true)
              {
                 showDialog(context: pageContext, builder: (dialogContext){
                  return AlertDialog(
                    title: Text('Enter Password'),
                    content: TextField(
                      controller: txtnotepassword,
                    ),
                    actions: [
                      TextButton(onPressed: (){
                        if(txtnotepassword.text=='123')
                          {
                            print('Success');
                            // 关闭对话框,使用对话框专属context
                            Navigator.of(dialogContext).pop();
                            // 跳转页面,使用外层页面的context
                            Navigator.of(pageContext)
                                .push(MaterialPageRoute(builder: (context) {
                              return EditNoteScreen(
                                note: note,
                              );
                            }));
                          }
                        else
                          {
                            showMessage(dialogContext,'Wrong Password');
                            // 密码错误时可保留对话框,让用户重新输入(按需调整)
                            // Navigator.of(dialogContext).pop();
                          }
                      }, child: Text('Submit'))],
                  );
                });
                return;
              }

            Navigator.of(context)
                .push(MaterialPageRoute(builder: (context) {
              return EditNoteScreen(
                note: note,
              );
            }));
          },
          note: note,
        );
      }),
);

关键修改点

  • 提前获取外层页面的context(pageContext),跳转时使用该上下文,确保操作的是页面导航栈而非对话框的。
  • 移除回调末尾多余的pop(),仅在密码正确时关闭对话框;密码错误时可保留对话框让用户重新输入(可按需调整)。
  • 明确区分对话框的context(dialogContext)和页面的context,避免上下文混淆导致的导航异常。

内容的提问来源于stack exchange,提问作者Irfan Ganatra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:13:14