用户在flutter中输入1个字符后如何自动聚焦下一个文本字段

Hen*_*our 3 dart flutter flutter-dependencies flutter-layout flutter-web

我有 4 个小textFormField部件。一旦用户完成第一个文本字段,我想textField自动关注下一个文本字段。Flutter 有没有办法做到这一点?任何人请分享,提前感谢:)

在此输入图像描述

osa*_*xma 7

这可以在 Flutter 中以不同的方式完成,我将尝试分享其中最简单的一种。在给出答案之前,值得一提的是以下问题:

在 Flutter 中,当 TextField 为空时,退格键不会发送任何事件(即TextField.onChanged不会被调用)。在您的情况下,如果用户位于第三个字段并且按退格键返回到第二个字段,则如果没有链接问题中讨论的一些解决方法,则无法捕获该按键。简而言之,您需要添加一个零宽度空格字符(它不会被渲染,但存在于字符串中)来检测退格事件。

我提到这个问题是因为我正在分享一个利用零宽度空格字符(简称 zwsp)的示例。

在下面的示例中,我只是创建了两个列表,其中包含:

  • FocusNode对于每个字段
  • TextEditingController对于每个字段。

根据索引,您可以通过调用以下命令将焦点转移到特定字段: FocusNode.requestFocus()

同样,您可以通过调用删除焦点FocusNode.unfocus,也可以通过调用从任何地方删除任何焦点:(FocusScope.of(context).unfocus();在下面的示例中,它在插入最后一个字符后使用以隐藏键盘)。

话虽这么说,这里有一个完整的示例,您可以复制并粘贴来尝试一下:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;
  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(child: CodeField()),
    );
  }
}

/// zero-width space character
///
/// this character can be added to a string to detect backspace.
/// The value, from its name, has a zero-width so it's not rendered
/// in the screen but it'll be present in the String.
///
/// The main reason this value is used because in Flutter mobile,
/// backspace is not detected when there's nothing to delete.
const zwsp = '\u200b';

// the selection is at offset 1 so any character is inserted after it.
const zwspEditingValue = TextEditingValue(text: zwsp, selection: TextSelection(baseOffset: 1, extentOffset: 1));

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

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

class _CodeFieldState extends State<CodeField> {
  List<String> code = ['', '', '', ''];

  List<TextEditingController> controllers;
  List<FocusNode> focusNodes;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    focusNodes = List.generate(4, (index) => FocusNode());
    controllers = List.generate(4, (index) {
      final ctrl = TextEditingController();
      ctrl.value = zwspEditingValue;
      return ctrl;
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // give the focus to the first node.
      focusNodes[0].requestFocus();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    focusNodes.forEach((focusNode) {
      focusNode.dispose();
    });
    controllers.forEach((controller) {
      controller.dispose();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(
        4,
        (index) {
          return Container(
            width: 20,
            height: 20,
            margin: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
            ),
            child: TextField(
              controller: controllers[index],
              focusNode: focusNodes[index],
              maxLength: 2,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                counterText: "",
              ),
              onChanged: (value) {
                if (value.length > 1) {
                  // this is a new character event
                  if (index + 1 == focusNodes.length) {
                    // do something after the last character was inserted
                    FocusScope.of(context).unfocus();
                  } else {
                    // move to the next field
                    focusNodes[index + 1].requestFocus();
                  }
                } else {
                  // this is backspace event

                  // reset the controller
                  controllers[index].value = zwspEditingValue;
                  if (index == 0) {
                    // do something if backspace was pressed at the first field

                  } else {
                    // go back to previous field
                    controllers[index - 1].value = zwspEditingValue;
                    focusNodes[index - 1].requestFocus();
                  }
                }
                // make sure to remove the zwsp character
                code[index] = value.replaceAll(zwsp, '');
                print('current code = $code');
              },
            ),
          );
        },
      ),
    );
  }
}


Run Code Online (Sandbox Code Playgroud)