How to Make TextField on Focus in Flutter

TextField is an important widget in Flutter. As a developer, you may want to make the TextField focus so that users are easily prompted to enter their input. Let’s check how to make TextField focus in Flutter.

There are multiple ways to do this. One way is to use the autofocus property of the TextField widget.

See the code snippet given below

TextField(
        controller: _controller,
        autofocus: true,
        onSubmitted: (String value) {
          debugPrint(value);
        },
      ),

Following is the complete example for TextField auto focus.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter TextField Auto Focus'),
        ),
        body: const MyStatefulWidget());
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Padding(
      padding: const EdgeInsets.all(16.0),
      child: TextField(
        controller: _controller,
        autofocus: true,
        onSubmitted: (String value) {
          debugPrint(value);
        },
      ),
    ));
  }
}

The other way is to use FocusNode class and FocusScope class. This method can give you more control over focusing the TextFields.

FocusNode nodeFirst = FocusNode();
FocusNode nodeSecond = FocusNode();

TextField(
  focusNode: nodeFirst,
),

TextField(
  focusNode: nodeSecond,
),

ElevatedButton(
  onPressed: () {
    FocusScope.of(context).requestFocus(nodeSecond);
  },
  child: Text("Focus on Second TextField"),
),

This is how you make TextField focus in Flutter. I hope this tutorial will be helpful for you.

Similar Posts

Leave a Reply