Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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",
            ),
          ),
        ],
      ),
    );
  }
}
like image 383
polina-c Avatar asked Sep 19 '25 19:09

polina-c


2 Answers

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();
    }
  });
  ...
like image 50
polina-c Avatar answered Sep 22 '25 08:09

polina-c


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()});
    }
  ...
}
...
like image 25
Musa Biralo Avatar answered Sep 22 '25 10:09

Musa Biralo