Flutter web, disable focus on button on Tab press

781

Here is a solution that combines onEditingComplete and RawKeyboardListener.

onEditingComplete is used to catch ENTER key while RawKeyboardListener is used for the TAB key

enter image description here

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'),
            ),
          ],
        ),
      ),
    );
  }
}
Share:
781
woshitom
Author by

woshitom

Updated on December 27, 2022

Comments

  • woshitom
    woshitom over 1 year

    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?