Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

docs.flutter.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more

Flutter 3.38 and Dart 3.10 are here!Learn more

Handle changes to a text field

How to detect changes to a text field.

In some cases, it's useful to run a callback function every time the text in a text field changes. For example, you might want to build a search screen with autocomplete functionality where you want to update the results as the user types.

How do you run a callback function every time the text changes? With Flutter, you have two options:

  1. Supply anonChanged() callback to aTextField or aTextFormField.
  2. Use aTextEditingController.

1. Supply anonChanged() callback to aTextField or aTextFormField

#

The simplest approach is to supply anonChanged() callback to aTextField or aTextFormField. Whenever the text changes, the callback is invoked.

In this example, print the current value and length of the text field to the console every time the text changes.

It's important to usecharacters when dealing with user input, as text may contain complex characters. This ensures that every character is counted correctly as they appear to the user.

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

2. Use aTextEditingController

#

A more powerful, but more elaborate approach, is to supply aTextEditingController as thecontroller property of theTextField or aTextFormField.

To be notified when the text changes, listen to the controller using theaddListener() method using the following steps:

  1. Create aTextEditingController.
  2. Connect theTextEditingController to a text field.
  3. Create a function to print the latest value.
  4. Listen to the controller for changes.

Create aTextEditingController

#

Create aTextEditingController:

dart
// Define a custom Form widget.classMyCustomFormextendsStatefulWidget{constMyCustomForm({super.key});@overrideState<MyCustomForm>createState()=>_MyCustomFormState();}// Define a corresponding State class.// This class holds data related to the Form.class_MyCustomFormStateextendsState<MyCustomForm>{// Create a text controller. Later, use it to retrieve the// current value of the TextField.finalmyController=TextEditingController();@overridevoiddispose(){// Clean up the controller when the widget is removed from the// widget tree.myController.dispose();super.dispose();}@overrideWidgetbuild(BuildContextcontext){// Fill this out in the next step.}}
Note

Remember to dispose of theTextEditingController when it's no longer needed. This ensures that you discard any resources used by the object.

Supply theTextEditingController to either aTextField or aTextFormField. Once you wire these two classes together, you can begin listening for changes to the text field.

dart
TextField(controller:myController),

Create a function to print the latest value

#

You need a function to run every time the text changes. Create a method in the_MyCustomFormState class that prints out the current value of the text field.

dart
void_printLatestValue(){finaltext=myController.text;print('Second text field:$text (${text.characters.length})');}

Listen to the controller for changes

#

Finally, listen to theTextEditingController and call the_printLatestValue() method when the text changes. Use theaddListener() method for this purpose.

Begin listening for changes when the_MyCustomFormState class is initialized, and stop listening when the_MyCustomFormState is disposed.

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

Interactive example

#
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),          ],        ),      ),    );  }}
Was this page's content helpful?

Unless stated otherwise, the documentation on this site reflects Flutter 3.38.1. Page last updated on 2025-10-30.View source orreport an issue.


[8]ページ先頭

©2009-2025 Movatter.jp