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
相关产品推荐
相关产品推荐

