跳到主内容

焦点与文本字段

焦点与文本框的运作方式。

当一个文本框被选中并接受输入时,它被称为具有“焦点”。通常,用户通过点击来转移焦点到文本框,而开发者则通过使用本教程中描述的工具以编程方式将焦点转移到文本框。

管理焦点是创建具有直观流程的表单的基本工具。例如,假设你有一个带有文本框的搜索屏幕。当用户导航到搜索屏幕时,你可以将焦点设置到搜索词文本框。这允许用户在屏幕可见时立即开始输入,而无需手动点击文本框。

在本教程中,你将学习如何在文本框可见时立即赋予其焦点,以及如何在点击按钮时赋予文本框焦点。

在文本框可见时立即获取焦点

#

要使文本框在可见时立即获得焦点,请使用 autofocus 属性。

dart
TextField(
  autofocus: true,
);

有关处理输入和创建文本框的更多信息,请参阅教程的 表单 部分。

当点击按钮时获取文本框的焦点

#

与其立即将焦点转移到特定的文本框,你可能需要在稍后的时间点赋予文本框焦点。在现实世界中,你可能还需要响应 API 调用或验证错误来赋予特定的文本框焦点。在此示例中,在用户按下按钮后赋予文本框焦点,请按照以下步骤操作

  1. 创建一个 FocusNode
  2. FocusNode 传递给 TextField
  3. 在点击按钮时将焦点赋予 TextField

1. 创建一个 FocusNode

#

首先,创建一个 FocusNode。使用 FocusNode 在 Flutter 的“焦点树”中标识一个特定的 TextField。这允许你在接下来的步骤中赋予 TextField 焦点。

由于焦点节点是长生命周期对象,请使用 State 对象管理其生命周期。按照以下说明在 State 类的 initState() 方法中创建 FocusNode 实例,并在 dispose() 方法中清理它

dart
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Define the focus node. To manage the lifecycle, create the FocusNode in
  // the initState method, and clean it up in the dispose method.
  late FocusNode myFocusNode;

  @override
  void initState() {
    super.initState();

    myFocusNode = FocusNode();
  }

  @override
  void dispose() {
    // Clean up the focus node when the Form is disposed.
    myFocusNode.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Fill this out in the next step.
  }
}

2. 将 FocusNode 传递给 TextField

#

现在你已经有了 FocusNode,请在 build() 方法中将其传递给特定的 TextField

dart
@override
Widget build(BuildContext context) {
  return TextField(focusNode: myFocusNode);
}

3. 在点击按钮时将焦点赋予 TextField

#

最后,当用户点击浮动操作按钮时,将焦点赋予文本框。使用 requestFocus() 方法来执行此任务。

dart
FloatingActionButton(
  // When the button is pressed,
  // give focus to the text field using myFocusNode.
  onPressed: () => myFocusNode.requestFocus(),
),

互动示例

#
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(title: 'Text Field Focus', home: MyCustomForm());
  }
}

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Define the focus node. To manage the lifecycle, create the FocusNode in
  // the initState method, and clean it up in the dispose method.
  late FocusNode myFocusNode;

  @override
  void initState() {
    super.initState();

    myFocusNode = FocusNode();
  }

  @override
  void dispose() {
    // Clean up the focus node when the Form is disposed.
    myFocusNode.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Text Field Focus')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // The first text field is focused on as soon as the app starts.
            const TextField(autofocus: true),
            // The second text field is focused on when a user taps the
            // FloatingActionButton.
            TextField(focusNode: myFocusNode),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the button is pressed,
        // give focus to the text field using myFocusNode.
        onPressed: () => myFocusNode.requestFocus(),
        tooltip: 'Focus Second Text Field',
        child: const Icon(Icons.edit),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}