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

Flutter本地用户认证条件判断实现及登录逻辑问题排查

Flutter登录验证问题修复

你的代码核心问题是错误获取了TextField的输入内容:你直接调用usrname.toString(),这返回的是TextEditingController对象的字符串标识(类似TextEditingController@xxxx),根本不是用户输入的用户名,所以永远匹配不上"John"。

修复方法很简单:

  • 获取输入框文本要使用控制器的text属性,也就是usrname.text
  • 同理,密码验证也要用usrpass.text,如果需要验证密码的话
  • 可以先加个非空判断,避免空输入的情况

修正后的代码示例:

home: Scaffold(
  body: Center(
    child: AlertDialog(
      title: TextField(
        controller: usrname,
        decoration: const InputDecoration(hintText: "UserName"),
      ),
      content: TextField(
        controller: usrpass,
        decoration: const InputDecoration(hintText: "Pass"),
        obscureText: true, // 密码框建议隐藏输入
      ),
      actions: [
        ElevatedButton(
            onPressed: () {
              // 获取实际输入的用户名和密码,去除前后空格
              String usernameInput = usrname.text.trim();
              String passwordInput = usrpass.text.trim();

              // 先判断是否为空
              if (usernameInput.isEmpty || passwordInput.isEmpty) {
                print("请输入用户名和密码");
                return;
              }

              // 验证逻辑
              if (usernameInput == "John" && passwordInput == "123456") {
                // Get.to(HomePage());  
                print("登录成功");
              } else {
                print("用户名或密码错误");
              }
            },
            child: const Text("登录"))
      ],
    ),
  ),
);

额外提示:密码输入框加上obscureText: true可以隐藏输入内容,提升安全性;用trim()去除输入前后的空格,能避免用户误输入空格导致验证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:22:11