How to jump between controls with 'tab' in flutter for web?

3,400

Solution 1

It turned out the browser was taking the focus to other place. I added prevention of default browser behavior to the method 'build':

import 'dart:html';
...

@override
Widget build(BuildContext context) {  

  document.addEventListener('keydown', (dynamic event) {
    if (event.code == 'Tab') {
      event.preventDefault();
    }
  });
  ...

Solution 2

The solution that worked for me is a little different. I am on Flutter 2.0.1 with Dart 2.12.0

import 'dart:html';
import 'package:flutter/foundation.dart';
...

@override
Widget build(BuildContext context) {  

  if (kIsWeb) {
      document.addEventListener('keydown',
          (event) => {if (event.type == 'tab') event.preventDefault()});
    }
  ...
}
...
Share:
3,400
polina-c
Author by

polina-c

Updated on December 12, 2022

Comments

  • polina-c
    polina-c over 1 year

    I want user to be able to jump between controls with 'Tab' in my flutter web app. I followed this post to catch the key "Tab" and to navigate to next controls.

    When user presses 'Tab', cursor jumps to the next text box, but then, when user types, no letters appears in the text box.

    What can be wrong?

    Here is the code:

    class _LoginScreenState extends State<LoginScreen> {
      FocusNode _passwordFocus;
      FocusNode _emailFocus;
    
      @override
      void initState() {
        super.initState();
    
        _emailFocus = FocusNode();
        _passwordFocus = FocusNode();
      }
    
      @override
      void dispose() {
        _emailFocus.dispose();
        _passwordFocus.dispose();
    
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {        
    
        final TextEditingController emailController =
            new TextEditingController(text: this._email);
        final TextEditingController passwordController =
            new TextEditingController();
    
        return Scaffold(
          appBar: AppBar(
            title: Text('Sign In'),
          ),
          body: Column(
            children: <Widget>[
              RawKeyboardListener(
                child: TextField(
                  autofocus: true,
                  controller: emailController,
                  decoration: InputDecoration(
                    labelText: "EMail",
                  ),
                ),
                onKey: (dynamic key) {
                  if (key.data.keyCode == 9) {
                    FocusScope.of(context).requestFocus(_passwordFocus);
                  }
                },
                focusNode: _emailFocus,
              ),
              TextField(
                controller: passwordController,
                obscureText: true,
                focusNode: _passwordFocus,
                decoration: InputDecoration(
                  labelText: "Password",
                ),
              ),
            ],
          ),
        );
      }
    }