FocusScope.nextFocus() 意外跳过一个或多个 TextFormFields

Gio*_*gio 4 focus flutter

我想要一系列TextFormFields,用户可以通过在软键盘上按“下一步”(或在模拟器上测试时按硬键盘上的 Tab)来导航。我期待以下 Flutter 应用程序能够正常工作:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TextFormField Problem Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test Homepage'),
      ),
      body: Column(children: <Widget>[
        TextFormField(
          onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
          textInputAction: TextInputAction.next,
        ),
        TextFormField(
          onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
          textInputAction: TextInputAction.next,
        ),
        TextFormField(
          onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
          textInputAction: TextInputAction.next,
        ),
        TextFormField(
          onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
          textInputAction: TextInputAction.next,
        ),
        TextFormField(
          textInputAction: TextInputAction.done,
        ),
      ]),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

... 但是按下 Tab(在 DartPad 上)或按下“next”(在模拟器的软键盘上)会跳转到一个看似随机的字段,而不是跳转到下一个字段。更具体地说,它看起来像是FocusScope.of(context).nextFocus()“跳过”一个字段(或多个字段,有时,取决于运行情况),而不是直接转到下一个字段。

我假设即使不必明确指定我的s的属性(如StackOverflow 上的另一篇文章nextFocus()所示),它也可以自动找出下一个可聚焦小部件是什么。为什么不是这样?感谢您提供任何意见。ColumnfocusNodeTextFormField

我在 Android 模拟器(和 Dartpad)上使用 Flutter 1.22。

Rya*_*nes 7

Flutter 1.22 包含一项更改,可在您使用 textInputAction 时自动推进焦点:TextInputAction.next。但是,他们没有更新文档。

如果同时指定 onFieldSubmitted 和 textInputAction ,则不起作用,因为它具有调用 nextFocus 两次的效果。所以,Flutter 的变化是一个突破性的变化。

您不需要指定 onEditingComplete 回调并手动处理它。仅 TextInputAction.next 本身就足够了。

相关的 Flutter 变化在这里。另外,这里有一些讨论。

请注意,在 Flutter 更改的描述中,它说:“如果未指定 onEditingComplete,焦点将自动移动,但如果指定了 onEditingComplete,则必须手动移动。”