如何在Web上的Flutter中使用“标签”在控件之间跳转?

时间:2019-07-19 18:10:52

标签: user-interface flutter flutter-web

我希望用户能够在Flutter Web应用程序中使用“ Tab”的控件之间进行切换。 我跟随this post来捕捉键“ 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",
            ),
          ),
        ],
      ),
    );
  }
}

3 个答案:

答案 0 :(得分:2)

对我有用的解决方案有点不同。 我在使用 Dart 2.12.0 的 Flutter 2.0.1

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()});
    }
  ...
}
...

答案 1 :(得分:0)

原来,浏览器正在将焦点转移到其他地方。 我在方法“ build”中添加了防止默认浏览器行为的方法:

import 'dart:html';
...

@override
Widget build(BuildContext context) {  

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

答案 2 :(得分:0)

这对我有用,可以让标签正确地将我带到下一个字段:

onChanged: (text) {
  if (text.contains('\t')) {
    text = text.replaceAll('\t', '');
    _nextFocusNode.requestFocus();
  }
},