text
stringlengths
1
372
_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,
),
],
),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
focus and text fields
when a text field is selected and accepting input,
it is said to have “focus.”
generally, users shift focus to a text field by tapping,
and developers shift focus to a text field programmatically by
using the tools described in this recipe.
managing focus is a fundamental tool for creating forms with an intuitive
flow. for example, say you have a search screen with a text field.
when the user navigates to the search screen,