Mobile development · Intermediate · 26 min
Build and validate forms in Flutter
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Flutter 3.50.1 · Dart 3.14.0
You will build a patient registration form in Flutter 3.50 with tested validation rules, the right keyboards and autofill, a date picker, errors that screen readers announce and a submit button that cannot be pressed twice.
On this page
A form is where an app asks people to do work, and it is where most of them give up. The fixes are rarely clever: check each field at the right moment, say exactly what is wrong in plain words, bring up the keyboard that suits the field, let the phone fill in what it already knows, and never let a slow network turn one tap into two registrations.
In this tutorial you build a registration form for a clinic app. It asks for a full name, a phone number, an optional email address and a date of birth. You keep every validation rule in a plain Dart file with no Flutter imports and prove the rules with unit tests first. Then you build the screen around those rules with Form, GlobalKey<FormState> and TextFormField, add a calendar for the date of birth, make the errors reach TalkBack and VoiceOver users, and lock the button while the request runs. Widget tests check all of it without a device.
The rules are written for a global audience: names in any script pass, and phone numbers are checked against the international limit rather than one country's format, which matters when the same app serves patients in Lagos, Nairobi and Addis Ababa.
Step 1 · Create the project
Check that Flutter 3.50 is on your PATH:
flutter --versionThe first line should start with Flutter 3.50.1 (or a later 3.50 release) on the stable channel, with Dart 3.14 below it. If it shows an older version, run flutter upgrade.
Create a phone-only project in a practice folder that the last step deletes, and remove the starter test, which checks the counter app you are about to replace:
mkdir -p ~/flutter-forms-demo
cd ~/flutter-forms-demo
flutter create --platforms=android,ios patient_signup
cd patient_signup
rm test/widget_test.dartCheck it worked
cd ~/flutter-forms-demo/patient_signup
ls lib test
flutter analyzelib holds main.dart, test is empty, and flutter analyze ends with No issues found!.
Step 2 · Write the validation rules as plain Dart functions
A TextFormField takes a validator: a function that receives the field's text and returns null when the value is fine, or the message to show under the field when it is not. Nothing about that contract needs Flutter, so put the rules in their own file and keep widgets out of it. The rules then run in fast unit tests, and you could share the same file with a Dart server later.
cd ~/flutter-forms-demo/patient_signup
cat > lib/validators.dart <<'DART'
// Validation rules for the patient registration form. Each rule returns
// null when the value is acceptable, or a message to show the user.
String? validateFullName(String? value) {
final name = value?.trim() ?? '';
if (name.isEmpty) {
return 'Enter your full name';
}
if (name.runes.length > 100) {
return 'Use 100 characters or fewer';
}
return null;
}
/// Removes the spaces, hyphens, brackets and dots people type in numbers.
String normalisePhone(String value) {
return value.replaceAll(RegExp(r'[\s\-().]'), '');
}
final _phonePattern = RegExp(r'^\+?[0-9]{7,15}$');
String? validatePhone(String? value) {
final phone = normalisePhone(value ?? '');
if (phone.isEmpty) {
return 'Enter your phone number';
}
if (!_phonePattern.hasMatch(phone)) {
return 'Use 7 to 15 digits, with + and the country code if you can';
}
return null;
}
final _emailPattern = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
String? validateEmail(String? value) {
final email = value?.trim() ?? '';
if (email.isEmpty) {
return null;
}
if (!_emailPattern.hasMatch(email)) {
return 'Enter an email address like name@example.com';
}
return null;
}
String? validateDateOfBirth(DateTime? value, {required DateTime today}) {
if (value == null) {
return 'Choose your date of birth';
}
if (value.isAfter(today)) {
return 'Date of birth cannot be in the future';
}
final sixteenthBirthday = DateTime(value.year + 16, value.month, value.day);
if (sixteenthBirthday.isAfter(today)) {
return 'You need to be 16 or older to register yourself';
}
return null;
}
String formatDate(DateTime date) {
final month = date.month.toString().padLeft(2, '0');
final day = date.day.toString().padLeft(2, '0');
return '${date.year}-$month-$day';
}
DARTSome choices here are deliberate:
- Names are not pattern-checked. A rule such as "letters only" rejects apostrophes, hyphens, accents and whole scripts, so it fails people called Ngũgĩ wa Thiong'o or ብርሃኑ ተስፋዬ. The only checks are "not blank" and a length cap, counted in Unicode code points (
runes) rather than UTF-16 units. - Phone numbers are checked loosely. People type spaces and hyphens, so
normalisePhoneremoves them before checking, and the same function cleans the number you send to the server. The 15-digit ceiling comes from the ITU E.164 numbering plan. Real validation of a number is sending it a code by SMS; the form only catches typos. - Email is optional and the check is shallow. It catches a missing
@or domain. Whether the address exists is something only a confirmation email can tell you. - The date rule takes
todayas an argument instead of callingDateTime.now()itself, so a test can fix the date and the result never changes with the calendar. Someone born on 29 February needs no special case: 16 is a multiple of 4, so their 16th birthday always falls in a leap year (barring the year 2100) and is a real 29 February. If you changed the limit to an age that is not a multiple of 4, such as 18,DateTimewould roll the missing 29 February forward to 1 March, which is usually what you want.
Each message says what to do, not just that something is wrong. "Enter your phone number" is more useful than "Invalid input".
Check it worked
cd ~/flutter-forms-demo/patient_signup
flutter analyze lib/validators.dartThe analyser reports No issues found!. The file imports nothing, which you can confirm by searching it for import: there are no matches.
Step 3 · Prove the rules with unit tests
Write the tests before any widget exists. Each group covers what should pass and what should fail, including names in several scripts and numbers in the formats people really type:
cd ~/flutter-forms-demo/patient_signup
cat > test/validators_test.dart <<'DART'
import 'package:flutter_test/flutter_test.dart';
import 'package:patient_signup/validators.dart';
void main() {
group('validateFullName', () {
test('asks for a name when it is missing or blank', () {
expect(validateFullName(null), 'Enter your full name');
expect(validateFullName(' '), 'Enter your full name');
});
test('accepts names in any script', () {
expect(validateFullName('Chukwuemeka Obi'), isNull);
expect(validateFullName('Adébáyọ̀ Ọlá'), isNull);
expect(validateFullName("Ngũgĩ wa Thiong'o"), isNull);
expect(validateFullName('ብርሃኑ ተስፋዬ'), isNull);
});
test('caps the length', () {
expect(validateFullName('a' * 100), isNull);
expect(validateFullName('a' * 101), 'Use 100 characters or fewer');
});
});
group('validatePhone', () {
test('accepts numbers with spaces, hyphens and brackets', () {
expect(validatePhone('+234 803 123 4567'), isNull);
expect(validatePhone('+254-712-345-678'), isNull);
expect(validatePhone('0803 123 4567'), isNull);
});
test('rejects missing, short, long and lettered numbers', () {
expect(validatePhone(''), 'Enter your phone number');
expect(validatePhone('12345'), isNotNull);
expect(validatePhone('+1234567890123456'), isNotNull);
expect(validatePhone('0803 ABC 4567'), isNotNull);
expect(validatePhone('234+8031234567'), isNotNull);
});
test('normalisePhone keeps only digits and a leading plus', () {
expect(normalisePhone('+234 (803) 123-4567'), '+2348031234567');
});
});
group('validateEmail', () {
test('is optional', () {
expect(validateEmail(null), isNull);
expect(validateEmail(' '), isNull);
});
test('catches obvious typos', () {
expect(validateEmail('amina@example.com'), isNull);
expect(validateEmail('amina@'), isNotNull);
expect(validateEmail('amina.example.com'), isNotNull);
expect(validateEmail('amina@example'), isNotNull);
});
});
group('validateDateOfBirth', () {
final today = DateTime(2026, 11, 26);
test('asks for a date when none is chosen', () {
expect(validateDateOfBirth(null, today: today), 'Choose your date of birth');
});
test('rejects dates in the future', () {
expect(
validateDateOfBirth(DateTime(2026, 12, 1), today: today),
'Date of birth cannot be in the future',
);
});
test('accepts people from their 16th birthday', () {
expect(validateDateOfBirth(DateTime(2010, 11, 26), today: today), isNull);
expect(
validateDateOfBirth(DateTime(2010, 11, 27), today: today),
'You need to be 16 or older to register yourself',
);
expect(validateDateOfBirth(DateTime(1950, 5, 3), today: today), isNull);
});
test('treats a 29 February birthday as turning 16 on 29 February', () {
final leapDay = DateTime(2008, 2, 29);
expect(
validateDateOfBirth(leapDay, today: DateTime(2024, 2, 28)),
'You need to be 16 or older to register yourself',
);
expect(validateDateOfBirth(leapDay, today: DateTime(2024, 2, 29)), isNull);
});
});
test('formatDate pads months and days', () {
expect(formatDate(DateTime(2000, 1, 5)), '2000-01-05');
});
}
DART
flutter test test/validators_test.dartThese are ordinary Dart tests. package:flutter_test provides test, group and expect here, and flutter test runs them without building any widgets, so the whole file finishes in a few seconds.
Check it worked
flutter test ends with All tests passed! and a count of +13. To see a test catch a mistake, change {7,15} to {7,16} in lib/validators.dart and run flutter test test/validators_test.dart again: the "rejects missing, short, long and lettered numbers" test fails on the 16-digit number. Put {7,15} back and run it once more before you continue.
Step 4 · Open a calendar for the date of birth
Typing a date invites arguments about format (is 03/04 March or April?), so the form opens Material's date picker instead and shows the chosen date in one unambiguous format. Put the picker call in its own small file:
cd ~/flutter-forms-demo/patient_signup
cat > lib/date_picker.dart <<'DART'
import 'package:material_ui/material_ui.dart';
Future<DateTime?> pickDateOfBirth(
BuildContext context, {
DateTime? current,
required DateTime today,
}) {
return showDatePicker(
context: context,
initialDate: current ?? DateTime(today.year - 30),
firstDate: DateTime(1900),
lastDate: today,
helpText: 'Choose your date of birth',
);
}
DARTfirstDate and lastDate set the range the calendar lets people reach, so nobody can pick a date after today. initialDate is where the calendar opens: the date already chosen, or 1 January thirty years back, which puts most adults a few taps from their birthday instead of decades of swiping from this month. Tapping the year in the calendar's header switches to a year list, and the pencil icon switches to typing the date. The age rule stays in validateDateOfBirth, not in the picker's range, so the user sees a clear message rather than finding some dates greyed out with no reason given.
showDatePicker returns null when the user cancels, which is why the return type is Future<DateTime?>.
The file imports package:material_ui/material_ui.dart. Flutter 3.50 moved the Material widgets into their own material_ui package, which flutter create already lists in pubspec.yaml; the older package:flutter/material.dart import still works, but the analyser flags it as deprecated. Every Dart file with widgets in this tutorial uses the new import.
Check it worked
cd ~/flutter-forms-demo/patient_signup
flutter analyze libThe analyser reports No issues found!.
Step 5 · Build the form
Now the screen. It holds the form's state: a controller and a focus node for each field, the chosen date, a summary of errors and whether a request is running.
cd ~/flutter-forms-demo/patient_signup
cat > lib/registration_screen.dart <<'DART'
import 'package:material_ui/material_ui.dart';
import 'package:patient_signup/date_picker.dart';
import 'package:patient_signup/validators.dart';
class Registration {
const Registration({
required this.fullName,
required this.phone,
required this.email,
required this.dateOfBirth,
});
final String fullName;
final String phone;
final String? email;
final DateTime dateOfBirth;
}
typedef SubmitRegistration = Future<void> Function(Registration registration);
class RegistrationScreen extends StatefulWidget {
const RegistrationScreen({super.key, required this.onSubmit});
final SubmitRegistration onSubmit;
@override
State<RegistrationScreen> createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _phoneController = TextEditingController();
final _emailController = TextEditingController();
final _dateController = TextEditingController();
final _nameFocus = FocusNode();
final _phoneFocus = FocusNode();
final _emailFocus = FocusNode();
final _dateFocus = FocusNode();
DateTime? _dateOfBirth;
String? _errorSummary;
bool _submitting = false;
DateTime get _today => DateUtils.dateOnly(DateTime.now());
@override
void dispose() {
for (final controller in [
_nameController,
_phoneController,
_emailController,
_dateController,
]) {
controller.dispose();
}
for (final node in [_nameFocus, _phoneFocus, _emailFocus, _dateFocus]) {
node.dispose();
}
super.dispose();
}
Future<void> _chooseDate() async {
final picked = await pickDateOfBirth(
context,
current: _dateOfBirth,
today: _today,
);
if (picked == null || !mounted) return;
setState(() {
_dateOfBirth = picked;
_dateController.text = formatDate(picked);
});
}
Future<void> _submit() async {
final checks = [
(_nameFocus, validateFullName(_nameController.text)),
(_phoneFocus, validatePhone(_phoneController.text)),
(_emailFocus, validateEmail(_emailController.text)),
(_dateFocus, validateDateOfBirth(_dateOfBirth, today: _today)),
];
final failed = checks.where((check) => check.$2 != null).toList();
_formKey.currentState!.validate();
if (failed.isNotEmpty) {
setState(() {
_errorSummary = failed.length == 1
? '1 field needs fixing'
: '${failed.length} fields need fixing';
});
failed.first.$1.requestFocus();
return;
}
final email = _emailController.text.trim();
final registration = Registration(
fullName: _nameController.text.trim(),
phone: normalisePhone(_phoneController.text),
email: email.isEmpty ? null : email,
dateOfBirth: _dateOfBirth!,
);
setState(() {
_errorSummary = null;
_submitting = true;
});
try {
await widget.onSubmit(registration);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Registered ${registration.fullName}')),
);
} catch (_) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Could not register. Check your connection and try again.'),
),
);
} finally {
if (mounted) {
setState(() => _submitting = false);
}
}
}
@override
Widget build(BuildContext context) {
final summary = _errorSummary;
return Scaffold(
appBar: AppBar(title: const Text('Register as a patient')),
body: SafeArea(
child: Form(
key: _formKey,
child: AutofillGroup(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (summary != null) ...[
Semantics(
key: const Key('error-summary'),
container: true,
liveRegion: true,
child: Text(
summary,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 16),
],
TextFormField(
controller: _nameController,
focusNode: _nameFocus,
decoration: const InputDecoration(labelText: 'Full name'),
textCapitalization: TextCapitalization.words,
textInputAction: TextInputAction.next,
autofillHints: const [AutofillHints.name],
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: validateFullName,
),
const SizedBox(height: 16),
TextFormField(
controller: _phoneController,
focusNode: _phoneFocus,
decoration: const InputDecoration(
labelText: 'Phone number',
helperText: 'Include the country code, for example +234 803 123 4567',
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
autofillHints: const [AutofillHints.telephoneNumber],
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: validatePhone,
),
const SizedBox(height: 16),
TextFormField(
controller: _emailController,
focusNode: _emailFocus,
decoration: const InputDecoration(labelText: 'Email (optional)'),
keyboardType: TextInputType.emailAddress,
autocorrect: false,
textInputAction: TextInputAction.next,
autofillHints: const [AutofillHints.email],
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: validateEmail,
onFieldSubmitted: (_) => _chooseDate(),
),
const SizedBox(height: 16),
TextFormField(
controller: _dateController,
focusNode: _dateFocus,
readOnly: true,
decoration: const InputDecoration(
labelText: 'Date of birth',
helperText: 'Tap to choose from a calendar',
suffixIcon: Icon(Icons.calendar_today),
),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (_) => validateDateOfBirth(_dateOfBirth, today: _today),
onTap: _chooseDate,
),
const SizedBox(height: 24),
FilledButton(
onPressed: _submitting ? null : _submit,
child: _submitting
? const SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
semanticsLabel: 'Registering',
),
)
: const Text('Register'),
),
],
),
),
),
),
),
);
}
}
DARTThe file is long, so read it in four parts.
The form and its key
Form groups the fields, and GlobalKey<FormState> is how the screen reaches the form's state from outside its build method. _formKey.currentState!.validate() runs every field's validator, shows each message under its field and returns true only when all of them pass. The fields are TextFormFields rather than plain TextFields because a TextFormField registers itself with the nearest Form.
Each field sets autovalidateMode: AutovalidateMode.onUserInteraction, so it checks itself only after the user has changed it. A person who has not reached the phone field yet sees no red text there, while someone who types a short number sees the message straight away and sees it vanish once the number is long enough. Pressing Register checks everything, including fields nobody touched. Flutter also has AutovalidateMode.onUnfocus, which waits until the user leaves the field; it suits rules where half-typed input always looks wrong, such as an email address.
The date field is a read-only TextFormField. It cannot be typed into, but it still has a label, an error line, a place in the focus order and a validator, so it looks and behaves like the fields around it. Its validator ignores the text and checks _dateOfBirth, the real DateTime.
Keyboards, autofill and the Next key
keyboardType picks the soft keyboard: TextInputType.phone brings up a dial pad and TextInputType.emailAddress a layout with @ close at hand. textCapitalization: TextCapitalization.words capitalises each part of a name, and autocorrect: false stops the phone from "correcting" email addresses.
autofillHints tell Android and iOS what each field holds, so the phone can offer the user's own name, number and email from its saved details. AutofillGroup around the fields tells the platform they belong together. On a low-cost phone with a small screen, every field the phone fills in is one less round of typing on a cramped keyboard.
textInputAction: TextInputAction.next puts a Next key on the keyboard. When a field has no onEditingComplete of its own, Flutter moves focus to the next field in reading order when Next is pressed, so the name field hands over to the phone field with no extra code. The email field also sets onFieldSubmitted, which opens the calendar after focus moves on, because a keyboard cannot type into the read-only date field.
Errors that reach screen readers
Red text under a field is no help to someone who cannot see it. When Register finds problems, _submit does two things beyond showing the messages:
- It moves focus to the first field that failed, using that field's
FocusNode. TalkBack and VoiceOver read the focused field's label and its error, and a sighted user's keyboard opens in the right place. - It shows a short summary, such as "3 fields need fixing", inside
Semantics(liveRegion: true). A live region tells assistive technology that its content updates by itself; TalkBack reads it out when it appears, in the same way it reads a snack bar.
_submit decides which field to focus by calling the same plain validators directly. That is the payoff of keeping the rules in validators.dart: the form, the summary and the focus logic all use one definition of "wrong".
One tap, one request
_submitting is true from the moment the request starts until it ends, success or failure. While it is true the button's onPressed is null, which is how a Flutter button is disabled, and the label becomes a small spinner with a semanticsLabel, so a screen reader says "Registering" instead of nothing. On a slow or prepaid mobile connection people tap again when nothing seems to happen; a disabled button means the clinic gets one registration, not three.
The request itself is widget.onSubmit, passed in from outside. The screen does not know or care whether it calls your server, which lets the tests hand it a request they control. After the await, mounted is checked before using context, because the user may have left the screen while the request ran. If the request throws, the user sees a message that says what to try, and everything they typed is still in the fields.
Check it worked
cd ~/flutter-forms-demo/patient_signup
flutter analyze libThe analyser reports No issues found!. If it warns about use_build_context_synchronously, a context is used after an await without the mounted check in front of it.
Step 6 · Run the form on a device
Replace lib/main.dart. Until your server is ready, a stand-in function waits two seconds and succeeds, long enough to watch the button lock:
cd ~/flutter-forms-demo/patient_signup
cat > lib/main.dart <<'DART'
import 'package:material_ui/material_ui.dart';
import 'package:patient_signup/registration_screen.dart';
void main() {
runApp(const PatientSignupApp());
}
// Stands in for your server. Replace it with a real request, for example
// with package:http, and read the server address from configuration.
Future<void> pretendToRegister(Registration registration) async {
await Future<void>.delayed(const Duration(seconds: 2));
}
class PatientSignupApp extends StatelessWidget {
const PatientSignupApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Patient sign-up',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const RegistrationScreen(onSubmit: pretendToRegister),
);
}
}
DART
flutter analyzeStart it on any device that flutter devices lists:
cd ~/flutter-forms-demo/patient_signup
flutter runCheck it worked
flutter analyze reports No issues found!. On the device:
- Tap Register with the form empty. Three fields turn red, "3 fields need fixing" appears at the top, and the keyboard opens on Full name.
- Type a name and press Next: focus moves to Phone number and a dial pad appears. Type
12and the phone error shows at once; keep typing and it disappears once the number reaches 7 digits. - Press Next twice. After the email field, the calendar opens on January, thirty years ago. Pick a day and press OK, and the date appears in the field as
YYYY-MM-DD. - Tap Register. The button greys out with a spinner for two seconds, then a snack bar says "Registered" with the name. Tapping during those two seconds does nothing.
If you have an Android phone, turn on TalkBack in its accessibility settings and repeat step 1: TalkBack reads "3 fields need fixing" and then the Full name field and its error.
Step 7 · Test the form with widget tests
Widget tests drive the real screen on a simulated display with no device. Each test below covers one behaviour from the last step:
cd ~/flutter-forms-demo/patient_signup
cat > test/registration_screen_test.dart <<'DART'
import 'dart:async';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:patient_signup/registration_screen.dart';
const phoneError = 'Use 7 to 15 digits, with + and the country code if you can';
Finder field(String label) => find.widgetWithText(TextFormField, label);
EditableText editable(WidgetTester tester, String label) {
return tester.widget<EditableText>(
find.descendant(of: field(label), matching: find.byType(EditableText)),
);
}
Future<void> pumpScreen(WidgetTester tester, SubmitRegistration onSubmit) {
return tester.pumpWidget(
MaterialApp(home: RegistrationScreen(onSubmit: onSubmit)),
);
}
// Runs the frames for about a second, long enough for any dialog
// transition to finish.
Future<void> pumpForASecond(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(seconds: 1));
}
Future<void> pickFifteenthOfJanuary(WidgetTester tester) async {
await tester.tap(field('Date of birth'));
await pumpForASecond(tester);
expect(find.byType(DatePickerDialog), findsOneWidget);
await tester.tap(find.text('15').first);
await tester.pump();
await tester.tap(find.text('OK'));
await pumpForASecond(tester);
}
void main() {
testWidgets('an empty form shows errors and focuses the first one',
(tester) async {
final semantics = tester.ensureSemantics();
var calls = 0;
await pumpScreen(tester, (registration) async {
calls++;
});
await tester.tap(find.byType(FilledButton));
await pumpForASecond(tester);
expect(find.text('Enter your full name'), findsOneWidget);
expect(find.text('Enter your phone number'), findsOneWidget);
expect(find.text('Choose your date of birth'), findsOneWidget);
expect(calls, 0);
expect(editable(tester, 'Full name').focusNode.hasFocus, isTrue);
expect(
tester.getSemantics(find.byKey(const Key('error-summary'))),
isSemantics(label: '3 fields need fixing', isLiveRegion: true),
);
semantics.dispose();
});
testWidgets('a field checks itself once the user has typed in it',
(tester) async {
await pumpScreen(tester, (registration) async {});
await tester.enterText(field('Phone number'), '12');
await tester.pump();
expect(find.text(phoneError), findsOneWidget);
expect(find.text('Enter your full name'), findsNothing);
await tester.enterText(field('Phone number'), '+234 803 123 4567');
await tester.pump();
expect(find.text(phoneError), findsNothing);
});
testWidgets('fields ask for the right keyboard, autofill and focus order',
(tester) async {
await pumpScreen(tester, (registration) async {});
expect(editable(tester, 'Phone number').keyboardType, TextInputType.phone);
expect(
editable(tester, 'Email (optional)').keyboardType,
TextInputType.emailAddress,
);
expect(
editable(tester, 'Full name').autofillHints,
contains(AutofillHints.name),
);
expect(
editable(tester, 'Phone number').autofillHints,
contains(AutofillHints.telephoneNumber),
);
await tester.enterText(field('Full name'), 'Amina Bello');
await tester.testTextInput.receiveAction(TextInputAction.next);
await tester.pump();
expect(editable(tester, 'Phone number').focusNode.hasFocus, isTrue);
});
testWidgets('the date field opens a calendar and shows the chosen date',
(tester) async {
await pumpScreen(tester, (registration) async {});
await pickFifteenthOfJanuary(tester);
final year = DateTime.now().year - 30;
expect(find.text('$year-01-15'), findsOneWidget);
expect(find.text('Choose your date of birth'), findsNothing);
});
testWidgets('register is locked while the request runs', (tester) async {
final request = Completer<void>();
Registration? sent;
await pumpScreen(tester, (registration) {
sent = registration;
return request.future;
});
await tester.enterText(field('Full name'), ' Amina Bello ');
await tester.enterText(field('Phone number'), '+254 712 345 678');
await pickFifteenthOfJanuary(tester);
final button = find.byType(FilledButton);
await tester.ensureVisible(button);
await tester.tap(button);
await tester.pump();
expect(tester.widget<FilledButton>(button).onPressed, isNull);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(sent?.fullName, 'Amina Bello');
expect(sent?.phone, '+254712345678');
expect(sent?.email, isNull);
request.complete();
await tester.pump();
await tester.pump();
expect(find.text('Registered Amina Bello'), findsOneWidget);
expect(tester.widget<FilledButton>(button).onPressed, isNotNull);
});
}
DART
flutter testA few techniques are worth knowing:
find.widgetWithText(TextFormField, 'Phone number')finds a field by its label, which is how a user finds it too, andeditablereaches theEditableTextinside it to read the keyboard type, autofill hints and focus.tester.testTextInput.receiveAction(TextInputAction.next)presses the keyboard's Next key, so the focus test needs no device keyboard.ensureSemanticsturns on the semantics tree, andisSemanticschecks the summary is a live region with the right label, the same information TalkBack receives. It checks only the properties you name. It replaces the oldercontainsSemantics, which Flutter 3.50 marks as deprecated.pumpForASecondmoves the test clock on withpumpand a fixed duration instead ofpumpAndSettle, which keeps pumping until no animation is running. A spinner, or anything else that keeps animating, would makepumpAndSettlerun until its own ten-minute timeout, so a fixed duration keeps each test fast and predictable.- The last test controls the request with a
Completer: the request stays in flight until the test callscomplete(), so the test can look at the locked button in between, with the spinner still turning.
Check it worked
cd ~/flutter-forms-demo/patient_signup
flutter test 2>&1 | tee /tmp/flutter-forms-test.txt
grep -q 'All tests passed' /tmp/flutter-forms-test.txt
flutter analyzeflutter test runs both test files and ends with All tests passed! and +18, and the analyser reports No issues found!. To watch the lock test fail, change onPressed: _submitting ? null : _submit to onPressed: _submit in lib/registration_screen.dart and run flutter test: "register is locked while the request runs" fails on onPressed. Restore the line and run the tests again.
Step 8 · Clean up
Stop the app with q in the terminal running it. The next command deletes the practice project and everything in it; skip it if you want to keep building on the form, for example by storing registrations on the phone:
cd ~
rm -rf ~/flutter-forms-demoCheck it worked
ls ~/flutter-forms-demo reports that there is no such file or directory. The Flutter SDK in ~/develop/flutter is untouched.
Next steps
- Decide which fields a form needs at all, and in what order, before you build it: design a mobile form people can finish.
- Keep registrations on the phone until the network is back: store data in a Flutter app with Drift and SQLite.
- Revisit the layout widgets the form is built from: build Flutter screens from widgets, rows and columns.
Related tutorials
- Translate an Expo app with expo-localization and i18nextYou will have an Expo SDK 58 orders app in English, French, Swahili and Arabic that follows the phone's language, lets people pick another in settings, formats naira, shilling and CFA franc prices for their region, switches to right-to-left for Arabic and fails a check when a translation is missing.
- Sync Larkfield bookings offline first with an outbox queueYou will have a Larkfield app that saves every booking to an SQLite outbox first, sends it to a mock clinic API with an idempotency key when the phone is online or back in the foreground, retries with capped backoff and jitter, and offers the next free slot when a time has gone, all proven by Jest tests.
- Store Larkfield appointments on the phone with expo-sqliteYou will have the Larkfield app saving bookings to an SQLite database on the phone, with versioned migrations, bound parameters, all-or-nothing writes and an Appointments tab that updates itself, all covered by Jest tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials