**Title:** How to Focus and Unfocus on a TextField in Flutter: A Step-by-Step Guide
**Introduction:**
In Flutter, one of the most commonly used widgets is the TextField. It allows users to input text, and it’s an essential element in many apps. However, sometimes you might want to focus or unfocus a TextField programmatically. In this blog post, we’ll explore how to do just that.
**Focusing on a TextField in Flutter:**
To focus on a TextField, you can use the `focusNode` property and the `focus()` method. Here’s an example:
“`dart
import ‘package:flutter/material.dart’;
class FocusOnTextField extends StatefulWidget {
@override
_FocusOnTextFieldState createState() => _FocusOnTextFieldState();
}
class _FocusOnTextFieldState extends State {
final _focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Focus on TextField’),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
focusNode: _focusNode,
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: ElevatedButton(
onPressed: () {
_focusNode.requestFocus();
},
child: Text(‘Focus’),
),
),
],
),
),
);
}
}
“`
In this example, we create a `FocusNode` instance and assign it to the `focusNode` property of the `TextField`. Then, when the button is pressed, we call the `focusRequest()` method on the `FocusNode` to focus the TextField.
**Unfocusing from a TextField in Flutter:**
To unfocus from a TextField, you can use the `unfocus()` method. Here’s an example:
“`dart
import ‘package:flutter/material.dart’;
class UnfocusOnTextField extends StatefulWidget {
@override
_UnfocusOnTextFieldState createState() => _UnfocusOnTextFieldState();
}
class _UnfocusOnTextFieldState extends State {
final _focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Unfocus from TextField’),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
focusNode: _focusNode,
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: ElevatedButton(
onPressed: () {
_focusNode.unfocus();
},
child: Text(‘Unfocus’),
),
),
],
),
),
);
}
}
“`
In this example, when the button is pressed, we call the `unfocus()` method on the `FocusNode` to unfocus the TextField.
**Conclusion:**
In this blog post, we’ve learned how to focus and unfocus on a TextField in Flutter using the `focusNode` property and the `focus()` and `unfocus()` methods. By focusing on a TextField, you can bring the user’s attention to a specific field, and by unfocusing from a TextField, you can ensure that the user can’t accidentally type something elsewhere in your app. I hope this helps! Let me know if you have any questions or need further assistance.