In this example, I will share how to retrieve the value of a text field in flutter using the following complete code:
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 this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.