In this example, we will show you how to autofocus on the first TextField or any TextField in UI widget order. You may need to autofocus on TextField or TextFormField according to your need and automatically pop up the keyboard when the screen is opened. See the example below:
Method 1:
TextField(
autofocus: true,
)
You can set TRUE to the autofocus attribute of TextField if you want to autofocus on the field. You can only do this to the TextField where you want the autofocus in UI widget order.
Method 2:
Alternatively, you can also do this without the autofocus attribute using the focus node like below:
FocusNode myfocus = FocusNode();
Set the focus node to any TextField or TextFormField where you want to focus when the screen is opened.
TextField(
focusNode: myfocus,
)
Now, in the initial state method, you can focus programmatically:
@override
void initState() {
Future.delayed(Duration(seconds: 0),(){
myfocus.requestFocus(); //auto focus on second text field.
});
super.initState();
}
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();
@override
void initState() {
Future.delayed(Duration(seconds: 0),(){
myfocus.requestFocus(); //auto focus on second text field.
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Auto Focus on TextField"),
backgroundColor: Colors.redAccent
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
children: [
TextField(
autofocus: true,
),
TextField(
focusNode: myfocus,
),
],
)
)
);
}
}
In this way, you can autofocus on any TextField or TextFormField in Flutter.
Please Wait...
No any Comments on this Article