0

I have a simple flutter app where when I tap on the search icon, it should show me CupertinoSearchTextField() with the keyboard.

The good thing is that CupertinoSearchTextField() is showing when I tap the search icon, as you can see in the 2nd image, but the problem is that the keyboard does not pop up when I tap the search icon.

The search text field and the keyboard must show together so that the user can type directly.

-> Keep in mind, the user can still type, but user has to tap into the search field to activate the keyboard.

This is what my code looks like -

iOSAppBar(BuildContext context) {
    return CupertinoNavigationBar(
      backgroundColor: AppColors.blue,
      middle: state ? appBarTitle() : appBarSearchBox(),
      trailing: state ? appBarSearchIcon() : appBarCancelText(),
    );
  }

//this is the search field
Widget appBarSearchBox() {
    return CupertinoSearchTextField();
  }

enter image description here enter image description here

Haseeb
  • 87
  • 1
  • 13
  • 1
    Try this `autoFocus: true` From the property in the Text Field – Hamza Apr 08 '21 at 13:21
  • @Hamza tried but this specific property does not exist for CupertinoSearchTextField() widget. – Haseeb Apr 08 '21 at 13:29
  • then I guess you need to use `focusNode` check the 3rd answer here at https://stackoverflow.com/questions/60510427/how-to-show-the-keyboard-automatically-for-a-textfield-in-flutter – Hamza Apr 08 '21 at 13:35
  • Tried. Same issue. Keyboard not popping up. Have to tap the search text field to bring it up manually @Hamza – Haseeb Apr 08 '21 at 13:42

1 Answers1

1

Fist, create a focus node like this:

FocusNode yourFocusNode = FocusNode();

Then, add it to you CupertinoTextField

CupertinoSerchTextField(focusNode: yourFocusNode)

Then you can call

FocusScope.of(context).requestFocus(yourFocusNode);

or, if that does not work, try

yourFocusNode.requestFocus();

anywhere in your code to request focus. Don't forget to dispose your focusNode:

@override
void dispose() {
  myFocusNode.dispose();

  super.dispose();
}
Lars
  • 1,250
  • 9
  • 25
  • Awesome! Working perfectly. Thank you. Great explanation, easy to follow. I also noticed that when I tap on the 'cancel' button to close the keyboard, I get a flutter widget exception, but the app works fine, it does not crash, and this only happens whenI use FocusScope.of(context).requestFocus(yourFocusNode) in my build() method, yourFocusNode.requestFocus() does the job perfectly. However, do you have any idea why I would get a widget exception? Thank you! – Haseeb Apr 08 '21 at 16:54
  • @Haseeb can you provide the exact widget exception? – Lars Apr 09 '21 at 07:14