使用 flutter hooks 验证 TextFormField
Validate TextFormField with flutter hooks
我正在尝试迁移到 flutter_hooks,但我无法进行一些简单的 textformField 验证。
我有 2 个文本字段和一个按钮,我想在某些情况下(或者至少当文本字段为空时)显示错误
我的代码:
-控制器:
final _emailFieldController =
useTextEditingController.fromValue(TextEditingValue.empty);
final _password =
useTextEditingController.fromValue(TextEditingValue.empty);
final _onSavePressed = useState(false);
-小部件:
TextFormField(
decoration: InputDecoration(hintText: "Your email"),
controller: _emailFieldController,
),
TextFormField(
obscureText: true,
onSaved: (newValue) => print(newValue),
validator: (value) =>
_onSavePressed.value && _password.text.isEmpty
? "Can't be empty"
: null,
decoration: InputDecoration(
hintText: "Password",
),
controller: _password,
),
RaisedButton(
child: Text("Create"),
onPressed: () {
_onSavePressed.value = true;
},
)
感谢您的帮助!
使用您从验证器获得的 value
。例如
validator: (value) => value.isEmpty ? "Can't be empty" : null
让您可以访问密码字段的值。
我正在尝试迁移到 flutter_hooks,但我无法进行一些简单的 textformField 验证。
我有 2 个文本字段和一个按钮,我想在某些情况下(或者至少当文本字段为空时)显示错误
我的代码: -控制器:
final _emailFieldController =
useTextEditingController.fromValue(TextEditingValue.empty);
final _password =
useTextEditingController.fromValue(TextEditingValue.empty);
final _onSavePressed = useState(false);
-小部件:
TextFormField(
decoration: InputDecoration(hintText: "Your email"),
controller: _emailFieldController,
),
TextFormField(
obscureText: true,
onSaved: (newValue) => print(newValue),
validator: (value) =>
_onSavePressed.value && _password.text.isEmpty
? "Can't be empty"
: null,
decoration: InputDecoration(
hintText: "Password",
),
controller: _password,
),
RaisedButton(
child: Text("Create"),
onPressed: () {
_onSavePressed.value = true;
},
)
感谢您的帮助!
使用您从验证器获得的 value
。例如
validator: (value) => value.isEmpty ? "Can't be empty" : null
让您可以访问密码字段的值。