I have a Textfield then a Button then a Textfield. On Tab key press focus goes to first Textfield, on Tab key press again focus goes to the button. How can I ignore focus on button and give focus to second Textfield when Tab key is pressed 2 times?
I have a Textfield then a Button then a Textfield. On Tab key press focus goes to first Textfield, on Tab key press again focus goes to the button. How can I ignore focus on button and give focus to second Textfield when Tab key is pressed 2 times?
Here is a solution that combines onEditingComplete and RawKeyboardListener.
onEditingComplete is used to catch ENTER key while RawKeyboardListener is used for the TAB key
class HomePage extends HookWidget {
@override
Widget build(BuildContext context) {
final firstFieldFocusNode = useFocusNode();
final secondFieldFocusNode = useFocusNode();
return Scaffold(
body: Container(
padding: EdgeInsets.all(16.0),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RawKeyboardListener(
focusNode: firstFieldFocusNode,
onKey: (event) {
if (event.logicalKey == LogicalKeyboardKey.tab) {
secondFieldFocusNode.requestFocus();
}
},
child: TextFormField(
decoration: InputDecoration(labelText: 'First field'),
onEditingComplete: () {
print('ICI');
secondFieldFocusNode.requestFocus();
},
),
),
const SizedBox(height: 48.0),
ElevatedButton(onPressed: () {}, child: Text('CLICK ME')),
const SizedBox(height: 24.0),
TextFormField(
focusNode: secondFieldFocusNode,
decoration: InputDecoration(labelText: 'Second field'),
),
],
),
),
);
}
}
secondFieldFocusNode.requestFocus() inside onKey didn't work but this code does:
class HomePage extends HookWidget {
@override
Widget build(BuildContext context) {
final firstFieldFocusNode = FocusNode();
final secondFieldFocusNode = FocusNode();
return Scaffold(
body: Container(
padding: EdgeInsets.all(16.0),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RawKeyboardListener(
focusNode: firstFieldFocusNode,
onKey: (event) {
if (event.logicalKey == LogicalKeyboardKey.tab) {
firstFieldFocusNode.nextFocus(); <============= HERE
}
},
child: TextFormField(
decoration: InputDecoration(labelText: 'First field'),
onEditingComplete: () {
print('ICI');
secondFieldFocusNode.requestFocus();
},
),
),
const SizedBox(height: 48.0),
ElevatedButton(onPressed: () {}, child: Text('CLICK ME')),
const SizedBox(height: 24.0),
TextFormField(
focusNode: secondFieldFocusNode,
decoration: InputDecoration(labelText: 'Second field'),
),
],
),
),
);
}
}
I just replaced secondFieldFocusNode.requestFocus(); by firstFieldFocusNode.nextFocus();
Thank you Thierry for your help