Flutter中如何获取自定义TextInputField和PasswordInput的输入值
解决方案
问题原因
你给自定义组件TextInputField传入的controller和onChanged参数没有生效:仅在构造函数中声明了这两个参数,既没有将其定义为类的成员变量,也没有把参数绑定到内部嵌套的原生TextField组件上,所以输入变化的事件不会触发你传入的onChanged方法,controller也不会同步输入内容。
修复步骤
修改text-input-field.dart文件,按以下逻辑调整:
- 给
TextInputField类新增两个final成员变量:TextEditingController controller、ValueChanged<String> onChanged - 构造函数中完成两个参数的接收赋值
- 给内部的
TextField组件绑定controller和onChanged属性
完整修改后的代码
class TextInputField extends StatelessWidget { const TextInputField({ Key key, @required this.icon, @required this.hint, this.inputType, this.inputAction, @required this.controller, @required this.onChanged, }) : super(key: key); final IconData icon; final String hint; final TextInputType inputType; final TextInputAction inputAction; // 新增两个成员变量 final TextEditingController controller; final ValueChanged<String> onChanged; @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Padding( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Container( height: size.height * 0.08, width: size.width * 0.8, decoration: BoxDecoration( color: Colors.grey[500].withOpacity(0.5), borderRadius: BorderRadius.circular(16), ), child: Center( child: TextField( // 绑定两个属性到内部TextField controller: controller, onChanged: onChanged, decoration: InputDecoration( border: InputBorder.none, prefixIcon: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Icon( icon, size: 28, color: kWhite, ), ), hintText: hint, hintStyle: kBodyText, ), style: kBodyText, keyboardType: inputType, textInputAction: inputAction, ), ), ), ); } }
PasswordInput组件修改方法
和上述逻辑完全一致:给password-input.dart中的自定义类新增controller和onChanged成员变量,构造函数接收赋值后,绑定到内部的密码输入TextField上即可。
输入值获取方式
修复后有两种常用取值方式:
- 实时获取:通过你已经传入的
onChanged回调,每次输入内容变化时会触发回调拿到最新值 - 一次性获取:不需要依赖
onChanged存变量,在表单提交等需要取值的时机,直接读取_username.text、_password.text即可拿到输入框的当前内容
内容的提问来源于stack exchange,提问作者aashish sethi
相关产品推荐
相关产品推荐

