4

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",
            ),
          ),
        ],
      ),
    );
  }
}
4

2 回答 2

3

事实证明,浏览器正在将焦点转移到其他地方。我在“build”方法中添加了对默认浏览器行为的预防:

import 'dart:html';
...

@override
Widget build(BuildContext context) {  

  document.addEventListener('keydown', (dynamic event) {
    if (event.code == 'Tab') {
      event.preventDefault();
    }
  });
  ...
于 2019-07-19T18:10:52.337 回答
3

对我有用的解决方案有点不同。我在 Flutter 2.0.1 和 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()});
    }
  ...
}
...
于 2021-03-12T13:39:25.293 回答