Sub topic 10
Moving Focus Between Fields in Flutter
This chapter assumes basic Dart syntax, nullable types, closures, and Flutter layouts such as Column and Scaffold. It also assumes you know that a StatefulWidget keeps mutable state across rebuilds.
When a user completes one text field, a form should usually move focus to the next field. Focus is the framework's record of which widget receives keyboard input. A focused field displays the cursor and receives text from the keyboard.
Use FocusNode for explicit focus control
A FocusNode identifies a focusable widget. Create one node for each field that you want to control. Attach the node with the focusNode property, then call requestFocus on the next node.
Focus nodes are resources owned by your state object. Dispose of them when the state is removed.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: ProfileForm()));
}
class ProfileForm extends StatefulWidget {
const ProfileForm({super.key});
@override
State<ProfileForm> createState() => _ProfileFormState();
}
class _ProfileFormState extends State<ProfileForm> {
final _nameFocus = FocusNode();
final _emailFocus = FocusNode();
final _formKey = GlobalKey<FormState>();
@override
void dispose() {
_nameFocus.dispose();
_emailFocus.dispose();
super.dispose();
}
void _submit() {
if (_formKey.currentState!.validate()) {
FocusManager.instance.primaryFocus?.unfocus();
debugPrint('Form submitted');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
focusNode: _nameFocus,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(labelText: 'Name'),
validator: (value) =>
value == null || value.trim().isEmpty
? 'Enter your name'
: null,
onFieldSubmitted: (_) {
_emailFocus.requestFocus();
},
),
TextFormField(
focusNode: _emailFocus,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.done,
decoration: const InputDecoration(labelText: 'Email'),
validator: (value) =>
value == null || !value.contains('@')
? 'Enter a valid email'
: null,
onFieldSubmitted: (_) => _submit(),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _submit,
child: const Text('Save'),
),
],
),
),
),
);
}
}textInputAction changes the action button shown by the software keyboard. next tells the user that another field follows. done indicates that editing is complete. These labels do not move focus by themselves when you need custom behavior, so onFieldSubmitted handles the action.
Understand the focus sequence
The first field calls requestFocus on the second field. The second field calls _submit, which validates the form and removes focus after successful validation.
You can also let Flutter follow its default focus order by using onEditingComplete: () => FocusScope.of(context).nextFocus(). This is convenient for simple layouts. Explicit FocusNode references are clearer when fields are conditional, arranged in a custom order, or split across multiple sections.
Avoid common focus problems
- Use
TextInputAction.nextonly when another editable field follows. - Use
TextInputAction.donefor the final field. - Do not call
unfocusbefore moving to the next field. - If validation fails, keep focus on the field that needs correction.
- Use
FocusManager.instance.primaryFocus?.unfocus()when tapping a button should hide the keyboard. - Test keyboard navigation on a real device or emulator because hardware and software keyboards can behave differently.
Exercise
In the example, what should happen when the user presses the keyboard action button while the Name field is focused?
Show answer
The onFieldSubmitted callback should call _emailFocus.requestFocus(), moving keyboard input to the Email field.