31

I have a TextField in Flutter of which I want to automatically select the text and show the keyboard. I can select the text through a TextEditingController, but even with a FocusNodes requestFocus the keyboard isn't shown, when the Widget opens.

How to automatically open the keyboard for a TextField?

relascope
  • 4,399
  • 4
  • 22
  • 27

4 Answers4

39

You can use the autofocus:true property of the TextField:

Whether this text field should focus itself if nothing else is already focused.

So whenever the widget appears on screen, if theres nothing else with the keyboard focus, the focus will automatically be directed to it, thus opening the keyboard.

TextField(TextEditingController: controller, 
         focusNode: focusNode,
         autofocus:true)
Andrew
  • 7,548
  • 7
  • 50
  • 72
Naslausky
  • 3,443
  • 1
  • 14
  • 24
14

You can set the autofocus property on TextField to true:

TextField(
  autofocus: true,
);

Hope it helps!

fvillalba
  • 963
  • 10
  • 18
7
class yourWidget extends StatelessWidget {  
FocusNode inputNode = FocusNode();
// to open keyboard call this function;
void openKeyboard(){
FocusScope.of(context).requestFocus(inputNode)
}

@override
Widget build(BuildContext context) {
  TextFormField(
   //assign the  node like this
   focusNode: inputNode,
   autofocus:true,)


}
John Bryan
  • 151
  • 2
  • 4
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Adrian Mole Oct 12 '20 at 14:27
1

I have done this just using:

autofocus: true,

But if you want more control over your TextField / TextFormFeild keyboard you can use:

1. First declare a focus node object:

FocusNode focusNode = FocusNode();  // declear a focusNode object

2. On TextFeild / TextFormFeild, just do like below:

    focusNode: focusNode,   // assign focusNode object on focusNode value
    autofocus: true,       // make autofocus true for first auto open keyboard

3. Just call this function when you want to open your keyboard:

   void openKeyboard () {
       FocusScope.of(context).requestFocus(inputNode); 
    }

This is an example of how you can use it. Using that format you can open the keyboard automatically / you have complete control over whether or not you need to open the keyboard.

I hope this will fix your issue.

Md. Al-Amin
  • 690
  • 3
  • 13