In this example, you will learn how to programmatically focus or unfocus on TextField or TextFormField in Flutter. Sometimes you may need to focus manually with code to focus or unfocus from TextField in Flutter. See the example below and learn how to do it.
First, create a Focus Node:
FocusNode myfocus = FocusNode();
Now, apply this created focus node to TextField or TextFormField:
TextField(
focusNode: myfocus,
)
Now, you can focus or unfocus from TextField using this Focus Node:
myfocus.requestFocus();
Use the method requestFocus()
of Focus Node to focus on TextField.
myfocus.unfocus();
Use the method unfocus()
of Focus Node to unfocus on TextField.
import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
FocusNode myfocus = FocusNode(); //create focus node
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Focus/Unfocus on TextField"),
backgroundColor: Colors.redAccent
),
body: Container(
child: Column(
children: [
TextField(
focusNode: myfocus, //apply focus node
),
ElevatedButton(
onPressed: (){
myfocus.requestFocus(); //focus
},
child: Text("Focus on TextField")
),
ElevatedButton(
onPressed: (){
myfocus.unfocus(); //unfocus
},
child: Text("Unfocus from TextField")
)
],
)
)
);
}
}
In this way, you can focus or unfocus on TextField in Flutter.
Please Wait...
No any Comments on this Article