text
stringlengths
1
474
Supply the TextEditingController to either a TextField
or a TextFormField. Once you wire these two classes together,
you can begin listening for changes to the text field.
<code_start>TextField(
controller: myController,
),<code_end>
<topic_end>
<topic_start>
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.
<code_start>void _printLatestValue() {
final text = myController.text;
print('Second text field: $text (${text.characters.length})');
}<code_end>
<topic_end>
<topic_start>
Listen to the controller for changes
Finally, listen to the TextEditingController and call the
_printLatestValue() method when the text changes. Use the
addListener() method for this purpose.Begin listening for changes when the
_MyCustomFormState class is initialized,
and stop listening when the _MyCustomFormState is disposed.
<code_start>@override
void initState() {
super.initState();
// Start listening to changes.
myController.addListener(_printLatestValue);
}<code_end>
<code_start>@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();
}<code_end>
<topic_end>
<topic_start>
Interactive example
<code_start>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,
),
],