0

I'm trying to move to flutter_hooks but I can't get some simple textformField validation to work.

I have 2 textfields and a button and I'd like to show an error on some conditions (or at least when the textfield is empty)

My code: -controllers:

final _emailFieldController =
        useTextEditingController.fromValue(TextEditingValue.empty);

    final _password =
        useTextEditingController.fromValue(TextEditingValue.empty);
    final _onSavePressed = useState(false);

-widgets:

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;
                  },
                )

Thank you for your help!

user1445685
  • 793
  • 1
  • 11
  • 25

2 Answers2

1

Use value that you get from validator. for example

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

gives you access to the value of the password field.

  • Got it. but how can I trigger the validation from the button? – user1445685 Sep 30 '20 at 18:57
  • 2
    Wrap your `TextFormField` in a `Form`, then assign a key to the form. `final _key = GlobalKey();` then on your Form, do `Form( key: _key, )` then you can access methods on the `currentState` of the key. So for example, `_key.currentState.validate()` you can call from anywhere that can access the key. –  Sep 30 '20 at 18:59
  • 1
    Thank you very much. For some reason I thought the form could only be used in stateful widgets so I didn't think about that solution. Thank you so much for your time! – user1445685 Sep 30 '20 at 19:15
  • @user1445685 np! –  Sep 30 '20 at 20:12
0

I'm doing just that in my Flutter tutorial:

class BookDetailsPage extends HookWidget {
 BookDetailsPage({
Key? key,
this.bookId,
}) : super(key: key);

final int? bookId;
final _bookFormKey = GlobalKey<FormState>();

@override
Widget build(BuildContext context) {
    final titleTextController = useTextEditingController(text: book?.title ?? '');
    final authorTextController = useTextEditingController(text: book?.author ?? '');
    final publishDateTextController = useTextEditingController(text: book?.publicationDate.toString() ?? '');

    return Scaffold(
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(AppDimensions.l),
          child: Form(
            key: _bookFormKey,
            autovalidateMode: AutovalidateMode.onUserInteraction,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                AppTextEdit(
                  labelText: LocaleKeys.books_details_book_title.tr(),
                  textInputType: TextInputType.name,
                  textEditingController: titleTextController,
                  validator: (value) => (value == null || value.isEmpty) ? '' : null,
                ),
                const SizedBox(height: AppDimensions.l),
                AppTextEdit(
                  labelText: LocaleKeys.books_details_author.tr(),
                  textEditingController: authorTextController,
                  textInputType: TextInputType.name,
                  validator: (value) => (value == null || value.isEmpty) ? '' : null,
                ),
                const SizedBox(height: AppDimensions.l),
                AppTextEdit(
                  labelText: LocaleKeys.books_details_publish_date.tr(),
                  textInputType: TextInputType.number,
                  textEditingController: publishDateTextController,
                  validator: (value) => (value == null || value.isEmpty || int.tryParse(value) == null) ? '' : null,
                ),
 ...
lomza
  • 9,412
  • 15
  • 70
  • 85