如何在带有 'tab' 的控件之间跳转 颤振 对于网络?



我希望用户能够在我的颤振网络应用程序中使用"Tab"在控件之间跳转。我按照这篇文章抓住了"Tab"键并导航到下一个控件。

当用户按"Tab"时,光标会跳转到下一个文本框,但随后,当用户键入时,文本框中不显示任何字母。

可能出了什么问题?

这是代码:

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

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

import 'dart:html';
...
@override
Widget build(BuildContext context) {  
  document.addEventListener('keydown', (dynamic event) {
    if (event.code == 'Tab') {
      event.preventDefault();
    }
  });
  ...

对我有用的解决方案有点不同。我在颤振 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()});
    }
  ...
}
...

最新更新