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 on focus so that users are easily prompted to enter their input. Let’s check how to make TextField on focus in Flutter.

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

TextField(
            keyboardType: TextInputType.text,
            autofocus: true,
            decoration: InputDecoration(
              hintText: 'Enter your name',
            ),
            controller: myController,
          ),

Following is the complete example.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter TextInput Focus Example',
      home: FlutterExample(),
    );
  }
}

class FlutterExample extends StatefulWidget {
  @override
  _FlutterExampleState createState() => _FlutterExampleState();
}

class _FlutterExampleState extends State<FlutterExample> {
  final myController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextInput on Focus'),
      ),
      body: Center(
        child: TextField(
          keyboardType: TextInputType.text,
          autofocus: true,
          decoration: InputDecoration(
            hintText: 'Enter your name',
          ),
          controller: myController,
        ),
      ),
    );
  }
}

The next 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 on focus in Flutter. I hope this tutorial will be helpful for you.

Leave a Comment

Your email address will not be published. Required fields are marked *