Skip to content

Latest commit

History

History
94 lines (50 loc) 路 2.63 KB

File metadata and controls

94 lines (50 loc) 路 2.63 KB

How to Validate a TextField in Flutter

How do you validate a TextField as the user types in Flutter?

Let's figure it out. 馃У

(hint: we'll use an AnimatedBuilder)

1


Let's start with a StatefulWidget that contains a TextField and an ElevatedButton.

This just shows the UI but doesn't do any validation.

2


Next, let's create a TextEditingController, dispose it as needed, and pass it to the TextField.

3


To validate the text, we can add:

  • an errorText getter variable
  • pass it to the TextField
  • use it to enable/disable our button with some conditional logic

4


But if we try this now, both the TextField error hint and the button UI don't update as the text changes.

Why? 馃

5


We forgot to tell Flutter to rebuild our widget when the text changes!

This could be fixed by setting a local state variable with a call to setState() in the TextField onChanged callback.

6


But we don't even need a local state variable in the first place because TextEditingController already contains the text value.

So how can we rebuild the widget when the text value changes?


We can wrap our widgets with an AnimatedBuilder and pass our TextEditingController to the animation argument:

7


This works because AnimatedBuilder takes an animation argument of type Listenable.

And TextEditingController extends ValueNotifier, which extends ChangeNotifier, which implements Listenable.

Here's how these classes are implemented in the Flutter SDK:

8


This means that we can pass instances of any of these classes to AnimatedBuilder.

And we can now validate our text on the fly:

9

Complete article: Flutter TextField Validation: How to work with TextEditingController, Form, and TextFormField


Found this useful? Show some love and share the original tweet 馃檹


Previous Next
How to Style an ElevatedButton in Flutter Responsive Flutter card layout with SizedBox & Center