How to Auto Focus on TextField in Flutter

To auto-focus on a TextField in Flutter, you can use the FocusNode class along with the TextField widget.

Here’s an example code snippet that demonstrates how to auto-focus on a TextField when the screen is loaded:

Example :

import 'package:flutter/material.dart';

void main() {
  runApp( MyScreen());
}

class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> {
  final _focusNode = FocusNode();

 @override
  void initState() {
    super.initState();
    // Auto-focus on the TextField when the screen is loaded
    Future.delayed(Duration.zero, () => _focusNode.requestFocus());
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              focusNode: _focusNode,
              decoration: InputDecoration(
                hintText: 'Enter your text here',
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }
}

output:

In the code above, we created a FocusNode instance _focusNode and assigned it to the focusNode property of the TextField. We then called the requestFocus() method of the _focusNode instance in the initState() method using Future.delayed(Duration.zero, () => _focusNode.requestFocus()) so that it runs after the widget tree has been built.

When the screen loads, the _focusNode.requestFocus() method is called, which focuses on the TextField, and the keyboard will appear, allowing the user to start typing immediately.

Finally, we dispose of the _focusNode instance in the dispose() method to prevent any memory leaks.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More