Jitesh Mohite
Jitesh Mohite

Reputation: 34250

Show error text of widget on button click

I have below code which needs to be get called on button click to show error Text, as condition failed on button click.
Error Text:

final confirmPassword = TextFormField(
      controller: widget.confirmPasswordController,
      obscureText: true,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
        hintText: 'Confirm Password',
        errorText: validatePassword(widget.confirmPasswordController.text)
            ? "Password should contains more then 5 character"
            : null,
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
      ),
    );

Button Click:

onPressed: () {
          if (validateEmail(widget.emailController.text) &&
              validatePassword(widget.passwordController.text) &&
              validatePassword(widget.confirmPasswordController.text)) {
              // launch new screen
          } else {
            // show the error text as above checks failed
          }
        }

How we can achive this? will setState() help us?

Upvotes: 0

Views: 1273

Answers (2)

Thepeanut
Thepeanut

Reputation: 3417

Using a Form widget.

Flutter has a good topic about it with complete examples: Build a form with validation

Upvotes: 0

iPatel
iPatel

Reputation: 47099

You can achieve it by use Form widget with key. Like

Declare

GlobalKey<FormState> _globalFormKey = GlobalKey();

and set it to

Form(
     key: _globalFormKey,
     .
     .
     .
     child: 
)

Here you can use child as TextFormField and write on button click failure.

_globalFormKey.currentState.validate()

For more info Form widget

~PS: Instead of check validation out of TextFormField, It has own property validator. Search and use it.

Upvotes: 1

Related Questions