Handling User Input
Handling User Input
In this chapter, we will explore some of the different input widgets, how to validate user input and provide errors or feedback to the user, and how to submit the data for processing.
example dart in the Chapter 05 folder; it holds only the complete SignUpForm of the last section, so no code block below is labelled. The repository's constructors use the older {Key? key}) : super(key: key) form instead of {super.key}, and it has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).Chapter overview
Structure
- Buttons
- Capturing text input
- Pickers, selectors, and dropdowns
- Radios, checkboxes, switches, and segmented controls
- Sliders
- Forms and FormFields
- Building a simple signup form
Objectives
Runnable example
SignUpForm, assembled from the chapter's fragments, are also available as a runnable input gallery with widget tests in examples/flutter_for_jobseekers_ch05/. The code on this page is shown as the book prints it, with conversion glitches fixed.Buttons
There are many different types of buttons in Flutter. Between both the Material and Cupertino packages, there are several styles from which we can choose. Additionally, we can create our own buttons using whatever widgets we want. Let us look at some of the buttons in their default configurations, then explore how to make our own button.
onPressed callback function. But what exactly is a callback function? For our purposes, a callback is a function that is passed into a widget as a parameter that can then be invoked from within the widget, but it will be run in the context of the widget's parent.If this does not make sense quite yet, do not worry. Let us look at some examples of buttons and how their callbacks work.
CupertinoButton
First, we will start by looking at CupertinoButton, the ubiquitous iOS-styled button available to us, thanks to the Cupertino package. Consider the following widgets (figure 5.1):
const CupertinoButton.filled(
onPressed: null,
child: Text('Disabled'),
),
CupertinoButton(
onPressed: () {},
child: const Text('Enabled'),
),
CupertinoButton.filled(
onPressed: () {},
child: const Text('Enabled'),
),

Figure 5.1: Various states of a CupertinoButton.
There are two variants of the CupertinoButton: CupertinoButton and CupertinoButton.filled.
CupertinoButton
CupertinoButton.filled
filled variety. The disabled state of the button is grey, whereas the enabled state is blue, such as with the third button.The color and disabled color can be changed by passing a Color to the color and disabledColor properties, respectively.
We can see that there are two states: enabled and disabled, but how are these states controlled, since the enabled property is read-only? According to the documentation, the button is disabled by default.
onPressed property to a non-null value. So, by providing a callback function, the button is enabled. Look at the code again and note that when the onPressed property is null, the button becomes a const.Let us talk about this onPressed callback function again. The default value we have been using is a simple () {}, which provides an empty function that performs no actions when it is invoked. Any code we want to run when the button is tapped will have to be inside the curly braces. If there was a callback value being passed to the function from the button, we would set that variable inside the parenthesis. However, the CupertinoButton, like other buttons, does not provide a value, so the parenthesis will be empty.
Try adding something between the curly braces, then tapping the button. Can you see your code being invoked?
() {
print("The button was pressed");
}
This is the mechanism by which we will eventually be able to submit a form. For now, let us briefly look at some of the other buttons available to us, and then we will learn to create our own.
Material buttons
From the Material package, here is an OutlinedButton (figure 5.2):
OutlinedButton(
onPressed: () {},
child: const Text('OutlinedButton'),
)

Figure 5.2: Visualizing the state changes of an OutlinedButton when tapping the lower right corner.
There is even a variant which allows us to use an icon, which can be invoked with the OutlinedButton.icon constructor and then passing an icon widget to it. Note that the text is moved to a label parameter, rather than the child parameter (figure 5.3).
OutlinedButton.icon(
onPressed: () {},
icon: const FlutterLogo(),
label: const Text('OutlinedButton'),
)

Figure 5.3: The icon variant of OutlinedButton.
The ElevatedButton has a similar look and feel to the CupertinoButton.filled with a material design take, including a subtle drop shadow (figure 5.4).
ElevatedButton(
onPressed: () {},
child: const Text('ElevatedButton'),
),

Figure 5.4: An ElevatedButton.
If you are using the Material package and need a button that is a bit simpler, try the TextButton (figure 5.5).
TextButton(
onPressed: () {},
child: const Text('TextButton'),
),

Figure 5.5: A simple TextButton.
Sometimes it doesn't make sense for your button to have text. In those instances, look toward the IconButton for a solution (figure 5.6).
IconButton(
icon: const Icon(Icons.flutter_dash),
onPressed: () {},
),

Figure 5.6: The default state (left) and hovered state (right) of an IconButton with Dash.
Whichever button you choose, be sure to explore the button's relevant style option(s) to customize it to your liking.
Custom buttons with GestureDetector
Let us say that none of these buttons give you quite what you are looking for, though. You have evaluated all of them and your app just needs something a bit more customized.
GestureDetector, we can turn any widget into a button. What is more, GestureDetector provides a nearly limitless array of possibilities when it comes to ways you can capture taps, swipes, and other gestures. For devices that support it, GestureDetector even has support for force presses.In fact, GestureDetector is so powerful, it can be used for far more than just custom buttons. Use it to drag items around the screen, pan and zoom, capture taps, double taps, triple taps, and more with ease. Here is an example where we turn a humble Container into a button that only works when you double tap it:
GestureDetector(
onDoubleTap: () {},
child: Container(
height: 100,
width: 100,
color: Theme.of(context).primaryColor,
),
),
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/buttons/buttons_demo.dart (all buttons of this section)
Capturing text input
When it comes to capturing text input from users, we have a few options available to us. The Cupertino package provides the CupertinoTextField widget, whereas the Material package gives us the TextField (figure 5.7).

Figure 5.7: TextField (top) and CupertinoTextField (bottom) with text entered in each.
There are a seemingly infinite number of options available to customize the look and feel of either input widget:
CupertinoTextField
BoxDecoration object in its decoration property.TextField
InputDecoration object in its decoration property.Both styles can have prefix and suffix widgets to display a widget on either the left or right side of the input. This could be useful for specifying a currency symbol, a password visibility toggle, and the like. Here, we have added both a prefix and suffix to either field (figure 5.8).
class TextFieldExample extends StatelessWidget {
const TextFieldExample({super.key});
@override
Widget build(BuildContext context) {
const Icon _prefixIcon = Icon(Icons.currency_bitcoin);
const Icon _suffixIcon = Icon(Icons.lock);
return Column(
children: const [
TextField(
decoration: InputDecoration(
icon: _prefixIcon,
suffixIcon: _suffixIcon,
),
),
SizedBox(height: 10),
CupertinoTextField(
prefix: _prefixIcon,
suffix: _suffixIcon,
),
],
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/text_input/text_field_example.dart
TextField, the book passes the prefix icon to icon, which is shown "before the input field and outside of the decoration's container". To place it inside the field, as the suffixIcon is, use prefixIcon, which "appears before the prefix or prefixText and before the editable part of the text field, within the decoration's container" (Flutter, n.d.-a).
Figure 5.8: Adding a prefix and suffix icon to each text input style.
There are plenty of other styling options available, so be sure to explore the various options when you decide to implement these widgets for yourself.
Almost more interesting than styling are the various functional options of these fields. Let us explore a few of these useful options, such as keyboardType, textInputAction, and inputFormatters.
keyboardType
The keyboardType property accepts a TextInputType object as its value. TextInputType has several options available to us to pick from:
<TextInputType>[text, multiline, number, phone, datetime, emailAddress, url, visiblePassword, name, streetAddress, none]
TextInputType now has two more constants, twitter ("Optimized for social media.") and webSearch ("Optimized for web searches."), as well as the numberWithOptions constructor (Flutter, n.d.-b).Think of a time when you were presented with a text input that wanted a numerical value, yet you were presented with a full keyboard, or a time when you were asked to enter your email address, but the @ key was hidden behind a function modifier. These are modern annoyances we all deal with from time to time, but the truth is that the tools to provide a better user experience are available for us to take advantage of, and we should do so whenever possible.
textInputAction
While we are on the subject, let us talk about the textInputAction. This is the default action of the enter key on the keyboard on mobile devices. Certainly, you have noticed that this button has changed from time to time. Sometimes it will display an arrow, or a carriage return symbol. Other times, it may display a send icon or a search icon. The options available to Android differ slightly from those on iOS, so it's a good idea to read up on the documentation. Here's a list of the available options:
<TextInputAction>[continueAction, done, emergencyCall, go, join, newline, next, none, previous, route, search, send, unspecified]
continueAction, emergencyCall, join, or route options, so ensure that you take this into account when writing your code.TextEditingController
Each text input can optionally have an associated TextEditingController associated with it. Generally, you want to create a variable outside of the build() method where you assign a TextEditingController to its value and then pass that variable into the text input's controller parameter. This could look something like the following:
class TextInputDemo extends StatefulWidget {
const TextInputDemo({super.key});
@override
State<TextInputDemo> createState() => _TextInputDemoState();
}
class _TextInputDemoState extends State<TextInputDemo> {
final TextEditingController _textController = TextEditingController();
@override
Widget build(BuildContext context) {
return TextField(
controller: _textController,
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/text_input/text_input_demo.dart (with dispose() and the digits-only formatter below)
Ok… you may be asking yourself, but why? An excellent question, indeed.
Read the text
TextEditingController to do so, as one example. You would do this by calling _textController.value.text.Clear the field
TextEditingController. You could also use it to clear the field when a user taps a button.There are lots of possibilities available to you, so it is worth spending some time thinking about and exploring the TextEditingController to see what else it is capable of.
@override
void dispose() {
_textController.dispose();
super.dispose();
}
inputFormatters
Finally, let us talk about the inputFormatters option. This parameter accepts a list of validation and formatting functions, which are applied from top to bottom each time the text in the field changes (for example, on each keypress). We can use this to do things like limiting the characters which are allowed to be typed into a field or automatically apply formatting to the text, such as entering dashes into phone numbers automatically.
In this example, we only allow numbers to be typed into a TextField:
TextField(
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
],
)
inputFormatters property accepts a list of input formatters, you can apply multiple formatters to input. Just keep in mind that the filters are applied from top to bottom.Pickers, selectors, and dropdowns
There are more inputs available than just text input. If you want to ask a user for their birthday, text input may not be the best option. Likewise, asking someone to choose an item from a list and type it in would be far less preferable to asking them to pick an item from a dropdown. Let us explore some of the input options which cover these use cases.
Material date and time pickers
Let us start by exploring the Material style date picker. Rather than being defined as a widget, the Material date picker is invoked using the function showDatePicker. Four parameter values are required for this function, but many other options are available. The required parameters are as follows:
context, firstDate and lastDate. initialDate is optional (DateTime? initialDate); "if initialDate is not null, it will show the month of initialDate" (Flutter, n.d.-c).Aside from context, the remaining three values expect a DateTime object. Several ways to get one:
DateTime.now()
DateTime.now() to get a value, which is, well, now.DateTime.parse()
DateTime object will be constructed from a string of text, which represents a given moment in time. The documentation on the method itself provides example strings that it can parse, but one such example could be DateTime.parse("2000-01-01").subtract()
DateTime.now().subtract(const Duration(days: 365)) would give you what you are looking for.final now = DateTime.now();, use DateTime(now.year - 1, now.month, now.day).Let us put all this knowledge into practice by creating a button that displays a material date picker.
ElevatedButton(
child: const Text("Press me"),
onPressed: () async {
await showDatePicker(
context: context,
firstDate: DateTime.now().subtract(const Duration(days: 365 * 50)),
lastDate: DateTime.now(),
initialDate: DateTime.parse("2000-01-01"),
);
},
)
This example will give us a date picker from where we can choose from any day in the past 50 years. Here is what that looks like (figure 5.9):

Figure 5.9: The Material date picker.
There is even a companion method, showTimePicker, which will allow you to choose a time of day the same way you would choose a date. The only required parameters are context and initialTime, which takes a TimeOfDay object. Here is what it looks like in practice (figure 5.10):

Figure 5.10: The Material time picker.
Cupertino pickers
The Material pickers are not the only game in town, though. How about the Cupertino style?
Material pickers, the Cupertino pickers are widgets. However, they take a bit more setup work.First, we will need a modal popup that we can pin to the bottom of the display. Inside our widget, we will define it something like this:
void _showDialog(BuildContext context, Widget child) {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) => Container(
height: 216,
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
color: CupertinoColors.systemBackground.resolveFrom(context),
child: SafeArea(
top: false,
child: child,
),
),
);
}
This will give us a bottom-aligned dialog in which we can display the picker. Next, we can invoke that dialog and add the CupertinoDatePicker as its child:
ElevatedButton(
child: const Text("Press me"),
onPressed: () => _showDialog(
context,
CupertinoDatePicker(
initialDateTime: DateTime.parse("2000-01-01"),
mode: CupertinoDatePickerMode.date,
onDateTimeChanged: (DateTime newDate) {
print('$newDate');
},
),
),
)
This will result in the following date picker being displayed (figure 5.11):

Figure 5.11: A Cupertino date picker with the dark theme applied.
By swapping out the picker for a CupertinoTimerPicker, you could determine a duration of time for, say, a timer. Here is what it would look like to get an hours and minutes duration (figure 5.12):
CupertinoTimerPicker(
mode: CupertinoTimerPickerMode.hm,
onTimerDurationChanged: (Duration duration) {
print('$duration');
},
)

Figure 5.12: A Cupertino timer picker with the dark theme applied.
Of course, the picker is far more versatile than just getting a date or a duration. In fact, it could be used for any arbitrary list of items. Let us look at an example where you can choose a day of the week. First, we need to define those days. We will do that in a list:
static const List<String> daysOfWeek = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
Next, we will use a CupertinoPicker to display each item in the list as an option. The itemExtent property tells the picker what height to give each item in the picker list.
CupertinoPicker(
itemExtent: 30,
useMagnifier: true,
children: daysOfWeek.map((day) => Text(day)).toList(),
onSelectedItemChanged: (int selectedItem) {
print(daysOfWeek[selectedItem]);
},
)
And just like that, we have taken an arbitrary list of items and created a picker from them (figure 5.13):

Figure 5.13: A Cupertino picker of an arbitrary list of items with the dark theme applied.
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/pickers/pickers_demo.dart (all Material and Cupertino pickers of this section)
DropdownButton
Finally, let us look at the DropdownButton widget, provided by the Material package. Like the generic picker from the Cupertino package, we can use this widget to allow users to pick from a list of items. Here, we have converted the Cupertino weekday picker into a material dropdown:
class WeekdayDropdown extends StatefulWidget {
static const List<String> daysOfWeek = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
const WeekdayDropdown({super.key});
@override
State<WeekdayDropdown> createState() => _WeekdayDropdownState();
}
class _WeekdayDropdownState extends State<WeekdayDropdown> {
String dropdownValue = WeekdayDropdown.daysOfWeek[0];
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
onChanged: (String? newValue) {
print(newValue);
},
items: WeekdayDropdown.daysOfWeek.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/pickers/weekday_dropdown.dart
onChanged only prints the new value. "The onChanged callback should update a state variable that defines the dropdown's value. It should also call State.setState to rebuild the dropdown with the new value" (Flutter, n.d.-d). The runnable copy sets dropdownValue = newValue! inside setState().Here it is in action (figure 5.14):

Figure 5.14: A Material dropdown.
Radios, checkboxes, switches, and segmented controls
Choosing an item from a list is not always the appropriate method, either. Sometimes what we need is to choose multiple items from a small group of similar items or a single item from a small number of items, which would not make sense in a dropdown. That is where this class of inputs comes in handy. Let us delve in.
Radio
When it comes to choosing items from a small, mutually exclusive list, the humble radio needs no introduction. Let us look at it in action.
class _MaybeState extends State<Maybe> {
String _value = "Yep";
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: const Text('Yep'),
leading: Radio<String>(
value: "Yep",
groupValue: _value,
onChanged: (String? value) {
setState(() {
_value = value!;
});
},
),
),
ListTile(
title: const Text('Nope'),
leading: Radio<String>(
value: "Nope",
groupValue: _value,
onChanged: (String? value) {
setState(() {
_value = value!;
});
},
),
),
],
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/selection/maybe.dart (MaybeRadio)
Radio.groupValue and Radio.onChanged are deprecated after Flutter 3.32: "Use a RadioGroup ancestor to manage group value instead" and "Use RadioGroup to handle value change instead" (Flutter, n.d.-e). On current Flutter, wrap the radios in a RadioGroup<String> that holds groupValue and onChanged, and give each Radio only its value. The runnable copy keeps the book's form, because the pinned Flutter 3.29 has no RadioGroup yet.This will produce two radios which a user can choose from: Yep and Nope. Here is what it looks like in action (figure 5.15):

Figure 5.15: Material radio buttons.
Segmented controls
This might feel out of place for an iOS user, though. Here is the same example using the CupertinoSegmentedControl, which ought to feel more appropriate on iOS:
class _MaybeState extends State<Maybe> {
String _value = "Yep";
@override
Widget build(BuildContext context) {
return CupertinoSegmentedControl(
groupValue: _value,
onValueChanged: (String? value) {
setState(() {
_value = value!;
});
},
children: const {
'Yep': Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text('Yep'),
),
'Nope': Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text('Nope'),
),
},
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/selection/maybe.dart (MaybeSegmented)
And, of course, here it is in action (figure 5.16):

Figure 5.16: A Cupertino segmented control.
There is even an iOS 13-style version, where the selector slides from option to option. This is, appropriately, a CupertinoSlidingSegmentedControl, and it can be used interchangeably with the CupertinoSegmentedControl, like the following (figure 5.17):
class _MaybeState extends State<Maybe> {
String _value = "Yep";
@override
Widget build(BuildContext context) {
return CupertinoSlidingSegmentedControl(
groupValue: _value,
onValueChanged: (String? value) {
setState(() {
_value = value!;
});
},
children: const {
'Yep': Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text('Yep'),
),
'Nope': Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text('Nope'),
),
},
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/selection/maybe.dart (MaybeSliding)

Figure 5.17: The Cupertino sliding segmented control.
Checkboxes
Finally, let us discuss checkboxes and selecting multiple items. The Material package gives us the Checkbox widget, which we are all familiar with.
tristate: true property is set.Here is an example of the three different states (figure 5.18):
class _CheckboxExampleState extends State<CheckboxExample> {
bool checkOneIsChecked = true;
bool checkTwoIsChecked = false;
bool? checkThreeIsChecked;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Checkbox(
value: checkOneIsChecked,
onChanged: (bool? value) {
setState(() {
checkOneIsChecked = value!;
});
},
),
Checkbox(
value: checkTwoIsChecked,
onChanged: (bool? value) {
setState(() {
checkTwoIsChecked = value!;
});
},
),
Checkbox(
tristate: true,
value: checkThreeIsChecked,
onChanged: (bool? value) {
setState(() {
checkThreeIsChecked = value;
});
},
),
],
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/selection/checkbox_example.dart

Figure 5.18: Checked, unchecked, and tri-state (null) checkboxes.
Switches
Checkboxes might feel somewhat out of place for iOS users, so consider offering them the option of a CupertinoSwitch, instead (figure 5.19):
class _SwitchExampleState extends State<SwitchExample> {
bool switchOne = true;
bool switchTwo = false;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CupertinoSwitch(
value: switchOne,
onChanged: (bool? value) {
setState(() {
switchOne = value!;
});
},
),
CupertinoSwitch(
value: switchTwo,
onChanged: (bool? value) {
setState(() {
switchTwo = value!;
});
},
),
],
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/selection/switch_example.dart (SwitchExample(material: true) swaps in the Material Switch)

Figure 5.19: An example of the CupertinoSwitch.
CupertinoSwitch and you find yourself wanting a Material variant, simply swap it out for the Switch widget to get that Material style (figure 5.20).
Figure 5.20: The Material style switch.
Sliders
Occasionally, it might make sense to offer the user the option to pick a number from a range. A common way to do this is by allowing the user to drag a slider. The Material Slider widget has plenty of options available:
Here is the Material slider (figure 5.21):
class _SliderExampleState extends State<SliderExample> {
double _currentSliderValue = 20;
@override
Widget build(BuildContext context) {
return Center(
child: Slider(
value: _currentSliderValue,
max: 100,
divisions: 5,
label: _currentSliderValue.round().toString(),
onChanged: (double value) {
setState(() {
_currentSliderValue = value;
});
},
),
);
}
}

Figure 5.21: The default Material slider state (top) and the active state when dragging (bottom).
Although the Cupertino variant lacks the label, many of the options are the same (figure 5.22):
class _SliderExampleState extends State<SliderExample> {
double _currentSliderValue = 20;
@override
Widget build(BuildContext context) {
return Center(
child: CupertinoSlider(
value: _currentSliderValue,
max: 100,
divisions: 5,
onChanged: (double value) {
setState(() {
_currentSliderValue = value;
});
},
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/sliders/slider_example.dart (SliderExample and CupertinoSliderExample)

Figure 5.22: The Cupertino slider.
Forms and FormFields
If you would like to collect a bunch of input from a user all at once and submit it to a backend system for processing, it makes sense to group the inputs together in a Form. Wrapping input fields in a Form widget is not required, but doing so has some advantages, for example:
Reset all inputs
Validate together
Save and reset state
The form key
The first thing you will need for your form is a Key. In this case, you will want to use a GlobalKey for the form key. Assign this to a variable outside of the build method, then set the Form's key property to the variable.
Now that you have got a Form with an associated key, you can check to see if all elements in the form are valid using _formKey.currentState!.validate() or reset the form back to its default state using _formKey.currentState!.reset(). Validating the Form will run the validator on each FormField which is a descendant of the Form.
FormField
This brings us to the FormField and validators. A FormField, when used inside a Form, makes it easier to do things like save the state of the FormField. When this happens, the onSaved callback is run on the field. If you have ever used an application that automatically saves your changes as soon as you are done editing a field (for example, typing your name into a field and the changes are saved automatically as soon as you tap out of the input), this is the same sort of mechanism.
FormField is not bound explicitly to the FormField being a descendant of a Form. In fact, you could attach a GlobalKey to the FormField itself and perform these same actions. What makes the Form powerful is that only a single GlobalKey is needed to save, reset, and validate all the ancestor FormField widgets of that Form.FormField widgets a Form acts on are its descendants, not its ancestors: "Call methods on FormState to save, reset, or validate each FormField that is a descendant of this Form" (Flutter, n.d.-f).FormField, itself, is somewhat abstract since it is not bound to any specific type of input method. There are other widgets that leverage and extend the FormField, such as TextFormField, which you may recognize as being very similar to our earlier example of the TextField.
TextField
onSaved and validator are unavailable.TextFormField
TextFormField is simply a TextField wrapped in a FormField. This opens for us the possibility of using the onSaved and validator methods. In addition, we are also able to set a default value inside the field, which we could not have done with a TextField.Validation
Now that we understand what a TextFormField is let us look at what validation is and how to put it to good use.
Let us look at an example. A user has been asked to enter their full legal name into a text field. An assumption you might make is that they will have both a given name and a surname. A validator on the input might check to make sure that at least two distinct words have been entered into the field. Here is what that could look like, in practice:
validator: (String? value) {
if (value.trim().split(' ').length < 2) {
return "Please enter your full, legal name.";
}
return null;
}
value is a String?, so value.trim() is not allowed until value has been checked for null. The signup form below adds that check (if (value == null || value.isEmpty)) before trim(), which the runnable copy also uses.Trim
We start by trimming any whitespace from the input because failing to do so would cause validation to pass as soon as the user enters some string and presses the spacebar.
Split
Next, we split the input into words, using a space as a delimiter. This takes each word that is separated by a space and adds it to a list.
Count
Then we check to see that there are at least two items in the list.
Return
If there are, validation was successful, so we return a null value. If validation fails, we return a message that describes the validation problem to the user.
GlobalKey when the submit button is pressed, as an example. If you want to automatically validate a field while the user is inputting data, you can supply an AutovalidateMode object to the field via its autovalidateMode parameter. Whichever option you choose, just remember that validation does not happen automatically by default.Building a simple signup form
Let us use some of what we have learned in the last section to build a simple signup form.
Name
E-mail address
Password, twice
Signup button
The form
The first thing we are going to need is a stateful widget for our signup form. This will allow us to validate the input and display any errors without losing the user's input. Let us call our new widget SignUpForm.
We are going to need a Form that will group together all our inputs so we can validate them all at once. To do that, we will also need our form key. The Form requires a child, so let us give it a Column where we will add our inputs later.
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [],
),
);
}
}
Text inputs and the button
With that out of the way, we are ready to start adding our text inputs. Each will need its own TextEditingController, and we can label them with a hintText by using the decoration parameter. Create your TextEditingController variables, just like you did with the form key, for each field and attach them to the proper field using the controller parameter. The following is an example key:
final TextEditingController _nameController = TextEditingController();
And here is an example of how to attach it to the input, then set the hint:
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
hintText: 'Name',
),
),
We will also want a button at the bottom of the list that we can use to submit the form later. Feel free to use any kind of button you want, although this example will use the ElevatedButton with some padding to separate it from the preceding inputs.
Padding(
padding: const EdgeInsets.only(top: 20),
child: ElevatedButton(
onPressed: () {},
child: const Text('Sign Up'),
),
),
We now have a basic form (figure 5.23), but it is far from complete:

Figure 5.23: Our basic form layout.
Validating the name
Since we know the name field is required, let us add a validator to it. As a reminder, the validator is a function that will run whenever we validate the form. It has a String? input and a String? return value.
Here is a very simple validator that checks to see if the user has entered any text in the field, then checks to see if they have entered their full name:
validator: (value) {
if (value == null || value.isEmpty) {
return 'Required';
}
if (value.trim().split(' ').length < 2) {
return "Please enter your full, legal name.";
}
return null;
},
Of course, this code will never run unless we try to validate the form, so we have no way of testing that it works. Let us fix that now. We want to validate the form whenever we press the button, so let us add some code into the onPressed argument that will call the form validation function.
onPressed: () {
if (_formKey.currentState!.validate()) {
// Process the form data.
}
},
Validating the e-mail address
@ symbol in the middle, with some sort of domain name on the right side. Plus, there are certain characters which are invalid in an e-mail address, like a semicolon. In short, e-mail address validation can become very complex, very quickly.A regular expression (or Regex, for short) is a pattern used to match character combinations in strings of text. Regular expressions are far outside the scope of this book, so you are encouraged to do some research on your own to understand them. At first glance, they can be terrifying and unapproachable, but with some practice, you will be able to break them down into smaller components that make far more sense.
Using the power of regular expressions, we can create a pattern that ought to match most valid e-mail addresses:
RegExp emailValidator = RegExp(
r'^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$',
caseSensitive: false,
multiLine: false,
);
Then, we just need to attach it to our e-mail field's validator function, like so:
validator: (value) {
if (value == null || value.isEmpty) {
return 'Required';
}
if (!emailValidator.hasMatch(value)) {
return 'Invalid email address';
}
return null;
},
email_validator to do the work for us. We will talk more about packages in Chapter 6: Using 3rd Party Libraries and External Files. For the purposes of illustration, however, the regular expression is sufficient.Validating the passwords
Next, let us tackle the password fields. We know that both fields need to be the same, so we only need to validate the actual input on one of them and make sure the second field matches it. There are a lot of valid special characters that we want to allow our users to use, so rather than listing all of them, let us use our old friend Regex to solve the problem.
If we consider normal characters to be all 26 characters of the Latin alphabet, along with the numbers 0 through 9, we can then consider special characters to be anything that is not a letter or a number. Luckily, a regular expression that matches all letters and numbers is very easy to write. Then, all we need to do is check that the value of the field is not matched by that regular expression, at which point we will know that we have a special character:
if (!value.contains(RegExp('[^A-Za-z0-9]'))) {
return 'Special character required';
}
We can add this check inside our validator alongside any other checks we want to perform, such as making sure the value is not empty. We also want to check our password to make sure it is at least eight characters long. See if you can figure out the test for that and check your work with the following code:
if (value.length < 8) {
return "Password is too short";
}
It seems like we have got all the validation done for the password complexity requirements, so let us add a validator to the password confirmation field. Like with the other fields, we want to ensure this field has been filled out, so check for that first. Then, we can use the TextEditingController that we assigned to the password field to get its current value and compare it to the input on this field.
if (value != _passwordController.text) {
return "Passwords do not match";
}
Hiding the password
To finish these fields off, we should specify a couple of additional parameters:
If you were so inclined, you could also add an icon to the field to toggle the password visibility. That would look something like the following:
TextFormField(
decoration: InputDecoration(
suffixIcon: IconButton(
onPressed: () {
setState(() {
_hidePassword = !_hidePassword;
});
},
icon: _hidePassword
? const Icon(Icons.visibility)
: const Icon(Icons.visibility_off),
),
),
obscureText: _hidePassword,
autocorrect: false,
enableIMEPersonalizedLearning: false,
enableSuggestions: false,
),
Just make sure you have created a _hidePassword bool that you can reassign, then tapping the eye icon will toggle visibility of the field and change the icon.
Submitting the values
To complete our signup form, we should do something with all the values we have collected once the form has been validated. Typically, you will pass these values to some sort of API or backend for processing, but we are just going to print them out to the debug console.
Find the if statement in your button's onPressed argument, where we call the validate method on the form. Any values in our form that we try to print from inside this statement will be guaranteed to be considered valid. Try printing the values from each of the fields, using the fields' controllers to get the value:
if (_formKey.currentState!.validate()) {
// Process the form data.
debugPrint('Name: ${_nameController.text}');
debugPrint('Email Address: ${_emailController.text}');
debugPrint('Password: ${_passwordController.text}');
}
Refer to the accompanying repository for the complete example of what we just built.
Runnable copy: examples/flutter_for_jobseekers_ch05/lib/forms/sign_up_form.dart (the complete form, assembled from the fragments above)
Companion code: the repository's example dart has the same button padding as above (EdgeInsets.only(top: 20.0)). Where the chapter is silent, the runnable copy differs from it: the repository gives the confirmation field its own visibility toggle (_hidePasswordConfirmation) and the hint Password (confirmation), while the copy shares one toggle and uses Confirm Password; the copy also adds dispose() and the e-mail keyboard type. The repository's e-mail RegExp lost its backslashes in conversion, so the copy keeps the pattern shown above.
Conclusion
Gathering information from users, whether that information is intent (such as by tapping a button) or direct input (such as typing their name into a field), is fundamental to creating any application. Validating that input is just as important, and you now have the tools to do just that.
We looked at how Cupertino and Material have different ways of accomplishing similar tasks, and you should now be thinking about building applications which feel at home to a user, regardless of what type of device they are using. Later in the book, we will talk more about this in depth.
In the upcoming chapter, we will learn how to find and use packages in our application that are provided by the community. We will learn how to add assets such as images to our application, then learn how to access them throughout the application. We have got a lot to cover, so take a break: stretch, grab a cup of tea, and when you are ready, let's move on.
Questions
- What is the difference between
MaterialandCupertinostyled widgets, and when would you use one over the other? - What is a callback function?
- What is the best way to add an icon to an
OutlinedButton? - How do you style a button, including changing its color?
- How do you disable a button?
- What widget can you use to convert an arbitrary widget, such as a
Container, into a button? - What widget can be used to detect a swipe gesture?
- How do you change the type of keyboard presented to a user on a mobile device when they tap a text field? For example, how would you present the user with a keyboard which is more appropriate for numerical input?
- What is a
TextEditingControllerused for? - In what order are input formatters applied?
- How can you prevent users from typing numbers in a text field and instead only allowing letters?
- You have a
DateTimeobject with a given date. How do you determine what the date will be precisely one year in the future from that date? - What is the key difference between the material date picker and the Cupertino date picker?
- What does the
mapmethod of aListdo? - What are some considerations when you want to use a group of
Radiobuttons? - How many states does a
Checkboxhave? - How can you limit the minimum and maximum values of a
Slider? - What is a
Form, and what's the benefit of using one? What are some cases in which aFormmight not be necessary? - What's the difference between a
TextFieldand aTextFormField? - How do you validate an input?
- What is a regular expression?
Key terms
Further reading
References
- BPB Publications. (n.d.). Flutter for Jobseekers (companion code repository). Retrieved from GitHub: https://github.com/bpbpublications/Flutter-for-Jobseekers (added, not in the book)
- Flutter. (n.d.-a). InputDecoration class. Retrieved from Flutter API: https://api.flutter.dev/flutter/material/InputDecoration-class.html (added, not in the book)
- Flutter. (n.d.-b). TextInputType class. Retrieved from Flutter API: https://api.flutter.dev/flutter/services/TextInputType-class.html (added, not in the book)
- Flutter. (n.d.-c). showDatePicker function. Retrieved from Flutter API: https://api.flutter.dev/flutter/material/showDatePicker.html (added, not in the book)
- Flutter. (n.d.-d). DropdownButton class. Retrieved from Flutter API: https://api.flutter.dev/flutter/material/DropdownButton-class.html (added, not in the book)
- Flutter. (n.d.-e). Radio class. Retrieved from Flutter API: https://api.flutter.dev/flutter/material/Radio-class.html (added, not in the book)
- Flutter. (n.d.-f). Form class. Retrieved from Flutter API: https://api.flutter.dev/flutter/widgets/Form-class.html (added, not in the book)
- Google. (n.d.). Material Design 3. Retrieved from Material Design: https://m3.material.io/ (added, not in the book)
Introduction to Widgets
How Flutter turns widgets into pixels, the difference between stateless, stateful and inherited widgets, and what BuildContext is.
Using 3rd Party Libraries and External Assets
The pubspec.yaml file, adding images and fonts as assets, the Pub package ecosystem, judging package quality, playing audio with a package, and popular packages.