When a text field is selected and accepting input, it is said to have “focus.”Generally, users can focus text fields by tapping on them, and developerscan focus text fields using the tools described in this recipe.

Managing focus is a fundamental tool for creating forms with an intuitiveflow. For example, say we have a search screen with a text field. Whenthe user navigates to the search screen, we can focus the search term text field.This allows the user to start typing as soon as the screenis visible, without needing to manually tap on the text field!

In this recipe, we’ll learn how to focus a text field as soon as it’s visibleas well as how to focus a text field when a button is tapped.

Focus a text field as soon as it’s visible

In order to focus a text field as soon as it’s visible, we can use theautofocus property.

  1. TextField(
  2. autofocus: true,
  3. );

For more information on handling input and creating text fields, please see theForms section of the cookbook.

Focus a text field when a button is tapped

Rather than immediately focusing a specific text field, we might need to focus atext field at a later point in time. In this example, we’ll see how to focus atext field after the user presses a button. In the real world, you may also needto focus a specific text field in response to an api call or a validation error.

Directions

  • Create a FocusNode
  • Pass the FocusNode to a TextField
  • Focus the TextField when a button is tapped

1. Create a FocusNode

First, we’ll need to create aFocusNode.We will use the FocusNode to identify a specific TextField in Flutter’s“focus tree.” This will allow us to focus the TextField in the next steps.

Since focus nodes are long-lived objects, we need to manage the lifecycleusing a State class. To do so, create the FocusNode instance inside theinitState method of a State class, and clean them up inside the disposemethod.

  1. // Define a Custom Form Widget
  2. class MyCustomForm extends StatefulWidget {
  3. @override
  4. _MyCustomFormState createState() => _MyCustomFormState();
  5. }
  6. // Define a corresponding State class. This class will hold the data related to
  7. // the form.
  8. class _MyCustomFormState extends State<MyCustomForm> {
  9. // Define the focus node. To manage the lifecycle, create the FocusNode in
  10. // the initState method, and clean it up in the dispose method
  11. FocusNode myFocusNode;
  12. @override
  13. void initState() {
  14. super.initState();
  15. myFocusNode = FocusNode();
  16. }
  17. @override
  18. void dispose() {
  19. // Clean up the focus node when the Form is disposed
  20. myFocusNode.dispose();
  21. super.dispose();
  22. }
  23. @override
  24. Widget build(BuildContext context) {
  25. // We will fill this out in the next step!
  26. }
  27. }

2. Pass the FocusNode to a TextField

Now that we have our FocusNode, we can pass it to a specific TextField inthe build method.

  1. class _MyCustomFormState extends State<MyCustomForm> {
  2. // Code to create the Focus node...
  3. @override
  4. Widget build(BuildContext context) {
  5. return TextField(
  6. focusNode: myFocusNode,
  7. );
  8. }
  9. }

3. Focus the TextField when a button is tapped

Finally, we’ll want to focus the text field when the user taps a floatingaction button! We’ll use therequestFocusmethod to achieve this task.

  1. FloatingActionButton(
  2. // When the button is pressed, ask Flutter to focus our text field using
  3. // myFocusNode.
  4. onPressed: () => FocusScope.of(context).requestFocus(myFocusNode),
  5. );

Complete example

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. title: 'Text Field Focus',
  8. home: MyCustomForm(),
  9. );
  10. }
  11. }
  12. // Define a Custom Form Widget
  13. class MyCustomForm extends StatefulWidget {
  14. @override
  15. _MyCustomFormState createState() => _MyCustomFormState();
  16. }
  17. // Define a corresponding State class. This class will hold the data related to
  18. // the form.
  19. class _MyCustomFormState extends State<MyCustomForm> {
  20. // Define the focus node. To manage the lifecycle, create the FocusNode in
  21. // the initState method, and clean it up in the dispose method
  22. FocusNode myFocusNode;
  23. @override
  24. void initState() {
  25. super.initState();
  26. myFocusNode = FocusNode();
  27. }
  28. @override
  29. void dispose() {
  30. // Clean up the focus node when the Form is disposed
  31. myFocusNode.dispose();
  32. super.dispose();
  33. }
  34. @override
  35. Widget build(BuildContext context) {
  36. return Scaffold(
  37. appBar: AppBar(
  38. title: Text('Text Field Focus'),
  39. ),
  40. body: Padding(
  41. padding: const EdgeInsets.all(16.0),
  42. child: Column(
  43. children: [
  44. // The first text field will be focused as soon as the app starts
  45. TextField(
  46. autofocus: true,
  47. ),
  48. // The second text field will be focused when a user taps on the
  49. // FloatingActionButton
  50. TextField(
  51. focusNode: myFocusNode,
  52. ),
  53. ],
  54. ),
  55. ),
  56. floatingActionButton: FloatingActionButton(
  57. // When the button is pressed, ask Flutter to focus our text field using
  58. // myFocusNode.
  59. onPressed: () => FocusScope.of(context).requestFocus(myFocusNode),
  60. tooltip: 'Focus Second Text Field',
  61. child: Icon(Icons.edit),
  62. ), // This trailing comma makes auto-formatting nicer for build methods.
  63. );
  64. }
  65. }

Text Field Focus Demo