在某些情况下,每次文本字段中的文本更改时运行回调函数会很有用。例如,您可能希望构建一个具有自动完成功能的搜索屏幕,并希望在用户输入时更新结果。

如何每次文本更改时都运行回调函数?在 Flutter 中,您有两种选择

  1. TextFieldTextFormField 提供一个 onChanged() 回调。
  2. 使用 TextEditingController

1. 为 TextFieldTextFormField 提供一个 onChanged() 回调

#

最简单的方法是为 TextFieldTextFormField 提供一个 onChanged() 回调。每当文本更改时,就会调用此回调。

在此示例中,每当文本更改时,都会将文本字段的当前值和长度打印到控制台。

处理用户输入时,使用 characters 包很重要,因为文本可能包含复杂字符。这确保了每个字符在用户眼中都能被正确计数。

dart
TextField(
  onChanged: (text) {
    print('First text field: $text (${text.characters.length})');
  },
),

2. 使用 TextEditingController

#

一个更强大但更复杂的方法是,将一个 TextEditingController 作为 TextFieldTextFormFieldcontroller 属性提供。

要在文本更改时收到通知,请使用以下步骤通过 addListener() 方法监听控制器

  1. 创建一个 TextEditingController
  2. TextEditingController 连接到文本字段。
  3. 创建一个函数以打印最新值。
  4. 监听控制器的更改。

创建一个 TextEditingController

#

创建一个 TextEditingController

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> {
  // Create a text controller. Later, use it to retrieve the
  // current value of the TextField.
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the
    // widget tree.
    myController.dispose();
    super.dispose();
  }

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

TextEditingController 连接到文本字段

#

TextEditingController 提供给 TextFieldTextFormField。一旦将这两个类连接起来,您就可以开始监听文本字段的更改了。

dart
TextField(controller: myController),

创建函数以打印最新值

#

您需要一个每次文本更改时都会运行的函数。在 _MyCustomFormState 类中创建一个方法,用于打印文本字段的当前值。

dart
void _printLatestValue() {
  final text = myController.text;
  print('Second text field: $text (${text.characters.length})');
}

监听控制器的更改

#

最后,监听 TextEditingController 并在文本更改时调用 _printLatestValue() 方法。为此,请使用 addListener() 方法。

_MyCustomFormState 类初始化时开始监听更改,并在 _MyCustomFormState 被释放时停止监听。

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

  // Start listening to changes.
  myController.addListener(_printLatestValue);
}
dart
@override
void dispose() {
  // Clean up the controller when the widget is removed from the widget tree.
  // This also removes the _printLatestValue listener.
  myController.dispose();
  super.dispose();
}

互动示例

#
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: 'Retrieve Text Input',
      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> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

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

    // Start listening to changes.
    myController.addListener(_printLatestValue);
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the widget tree.
    // This also removes the _printLatestValue listener.
    myController.dispose();
    super.dispose();
  }

  void _printLatestValue() {
    final text = myController.text;
    print('Second text field: $text (${text.characters.length})');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Retrieve Text Input')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              onChanged: (text) {
                print('First text field: $text (${text.characters.length})');
              },
            ),
            TextField(controller: myController),
          ],
        ),
      ),
    );
  }
}