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

Flutter中onPressed触发AlertDialog失效问题求助

Flutter登录表单对话框不弹出问题修复

你的代码核心问题在于_showAppLogin方法的判断逻辑错误,导致登录验证代码块从未执行,自然无法弹出对话框,也不会有控制台输出。

问题分析

TextEditingController的text属性永远不会返回null,输入框为空时它会返回空字符串""。而你写的条件if (name.text == null && password.text == null)永远为false,所以里面的登录验证和对话框代码完全没被触发。同时,你的Form组件没有设置GlobalKey,也未调用validate()方法,导致空输入的提示逻辑也无法正常工作。

修复方案

  1. 修正登录逻辑的判断条件,先处理空输入情况,再验证凭证是否正确
  2. 给Form添加GlobalKey,利用表单自带的校验功能
  3. 优化_showAppLogin方法逻辑,确保所有分支都能触发对应交互

修正后的完整代码

import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  bool _autovalidate = false;
  // 给Form添加GlobalKey用于校验
  final _formKey = GlobalKey<FormState>();

  // 登录凭证
  final String userName = 'admin';
  final String passWord = '123';

  // TextEditingController
  final name = TextEditingController();
  final password = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Expense Manager',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Form(
          key: _formKey, // 绑定FormKey
          autovalidateMode: _autovalidate ? AutovalidateMode.always : AutovalidateMode.disabled,
          child: Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15.0),
            ),
            child: Column(
              children: <Widget>[
                const Padding(padding: EdgeInsets.all(10.0)),
                Image(
                  image: const AssetImage('images/logo.png'),
                  height: 100.0,
                  width: 100.0,
                ),
                ListTile(
                  leading: const Icon(Icons.person),
                  title: TextFormField(
                    controller: name,
                    validator: (input) {
                      if (input?.isEmpty ?? true) {
                        return 'Enter Username';
                      }
                      return null;
                    },
                    decoration: const InputDecoration(labelText: 'Username'),
                  ),
                ),
                ListTile(
                  leading: const Icon(Icons.password),
                  title: TextFormField(
                    controller: password,
                    obscureText: true,
                    validator: (input) {
                      if (input?.isEmpty ?? true) {
                        return 'Enter Password';
                      }
                      return null;
                    },
                    decoration: const InputDecoration(labelText: 'Password'),
                  ),
                ),
                Container(
                  padding: const EdgeInsets.all(20.0),
                  child: ElevatedButton(
                    onPressed: _showAppLogin,
                    child: const Text(
                      'Login',
                      style: TextStyle(color: Colors.white),
                    ),
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      backgroundColor: Colors.redAccent,
                      padding: EdgeInsets.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showAppLogin() {
    // 先校验表单输入
    if (_formKey.currentState!.validate()) {
      // 输入合法,验证登录凭证
      if (name.text == userName && password.text == passWord) {
        _showAlertDialog('Login Successful');
      } else {
        _showAlertDialog('Invalid Credentials');
      }
    } else {
      // 输入不合法,开启自动校验
      setState(() {
        _autovalidate = true;
      });
    }
  }

  void _showAlertDialog(String message) {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        icon: const Icon(Icons.message_outlined),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('OK'),
          )
        ],
      ),
    );
  }
}

关键修改点

  • 给Form添加GlobalKey,触发表单校验逻辑
  • 重构_showAppLogin方法:先执行表单校验,再验证登录凭证,确保所有分支都能执行对应逻辑
  • 优化TextFormField的validator判断,避免空指针风险
  • 给对话框添加关闭按钮,提升用户体验
  • 移除不必要的late修饰符(变量初始化时无需late)

现在点击登录按钮,无论是空输入、错误凭证还是正确凭证,都会触发对应的对话框或输入提示,你也可以在_showAppLogin中添加debugPrint(name.text)测试控制台输出功能。

内容的提问来源于stack exchange,提问作者Nihar Shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:45:21