Flutter简易登录页导航失效:用户名密码变量为空排查
Flutter登录页面变量为空导致导航失效的解决方案
核心问题
你在buildTextFormField方法中传递Username和Password作为参数,但Dart中字符串是值类型,onSaved回调里的val=value!只会修改方法内部的局部变量,根本不会更新类成员变量Username和Password,这就是它们始终为空的原因。
修复方案
方案1:修改buildTextFormField传递onSaved回调
调整buildTextFormField方法,让它接受onSaved回调参数,直接在回调中更新类成员变量:
TextFormField buildTextFormField( IconData icon, String hint, bool isPassword, void Function(String?) onSaved) { return TextFormField( initialValue: "a", onSaved: onSaved, obscureText: isPassword, decoration: InputDecoration( prefixIcon: Icon(icon), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(40)), ), hintText: hint, ), ); }
调用时指定对应的onSaved逻辑:
// 用户名输入框 buildTextFormField(Icons.person, "Username", false, (value) => Username = value!), // 密码输入框 buildTextFormField(Icons.lock, "Password", true, (value) => Password = value!),
方案2:利用已定义的TextEditingController(更简洁)
你已经声明了emailController和passwordController,可以直接绑定到输入框,点击按钮时从控制器获取文本:
修改buildTextFormField绑定控制器:
TextFormField buildTextFormField( IconData icon, String hint, bool isPassword, TextEditingController controller) { return TextFormField( controller: controller, obscureText: isPassword, decoration: InputDecoration( prefixIcon: Icon(icon), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(40)), ), hintText: hint, ), ); }
调用时传入对应控制器:
buildTextFormField(Icons.person, "Username", false, emailController), buildTextFormField(Icons.lock, "Password", true, passwordController),
按钮点击逻辑改为从控制器取值:
onPressed: () { if(_formKey.currentState!.validate()) { String username = emailController.text; String password = passwordController.text; print("User: "+username); print("Password"+password); if(username=="a" && password=="a" ){ Get.to(Content()); } } }
额外修复:完善资源释放
别忘了在dispose方法中释放控制器,避免内存泄漏:
@override void dispose() { emailController.dispose(); passwordController.dispose(); super.dispose(); }
内容的提问来源于stack exchange,提问作者flutter app
相关产品推荐
相关产品推荐

