使用颤动钩子验证TextFormField

时间:2020-09-30 16:37:11

标签: flutter 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;
                  },
                )

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用从验证者那里获得的value。例如

validator: (value) => value.isEmpty ? "Can't be empty" : null

允许您访问密码字段的值。