In this article, you will learn How to retrieve the value of a text field in flutter which a user has entered into a 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | FloatingActionButton( // When the user presses the button, show an alert dialog containing the // text that the user has entered into the text field. onPressed: () { return showDialog( context: context, builder: (context) { return AlertDialog( // Retrieve the text the user has entered by using the // TextEditingController. content: Text(myController.text), ); }, ); }, tooltip: 'Show me the value!', child: Icon(Icons.text_fields), ); |
Here is an interactive example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Retrieve Text Input', home: MyCustomForm(), ); } } // Define a custom Form widget. class MyCustomForm extends StatefulWidget { @override _MyCustomFormState 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: Text('Retrieve Text Input'), ), body: Padding( padding: const EdgeInsets.all(16.0), 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: () { return 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: Icon(Icons.text_fields), ), ); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.