text
stringlengths
1
372
controller: myController,
);
<code_end>
<topic_end>
<topic_start>
3. display the current value of the text field
after supplying the TextEditingController to the text field,
begin reading values. use the text()
method provided by the TextEditingController to retrieve the
string that the user has entered into the text field.
the following code displays an alert dialog with the current
value of the text field when the user taps a floating action button.
<code_start>
FloatingActionButton(
// when the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// retrieve the text that the user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'show me the value!',
child: const Icon(Icons.text_fields),
),
<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 the 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 dispose() {
// clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('Retrieve text input'),
),
body: padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: myController,
),
),
floatingActionButton: FloatingActionButton(
// when the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// retrieve the text the that user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'show me the value!',
child: const Icon(Icons.text_fields),
),
);
}
}
<code_end>