Retrieving the value of a TextField component in Flutter typically involves several methods. Two common approaches are using TextEditingController and combining Form with TextFormField.
Method 1: Using TextEditingController
TextEditingController is a controller used to read and modify the content of a TextField. Here's an example of how to implement it:
-
Define
TextEditingControllerFirst, create an instance ofTextEditingControllerwithin your StatefulWidget and ensure proper disposal.dartclass MyWidget extends StatefulWidget { _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { final _controller = TextEditingController(); void dispose() { _controller.dispose(); super.dispose(); } Widget build(BuildContext context) { return Container( child: TextField( controller: _controller, ), ); } } -
Retrieve the
TextFieldvalue You can access the current value of theTextFieldat any time using_controller.text.dartvoid _printTextFieldValue() { print("Current input value is: ${_controller.text}"); }
Method 2: Using Form and TextFormField
When dealing with complex forms or requiring form validation, using Form with TextFormField is often a better choice.
-
Using
FormandTextFormFieldCreate aFormand embedTextFormFieldwithin it. Provide anonSavedcallback to capture the value when the form is saved.dartclass MyFormWidget extends StatefulWidget { _MyFormWidgetState createState() => _MyFormWidgetState(); } class _MyFormWidgetState extends State<MyFormWidget> { final _formKey = GlobalKey<FormState>(); String _userInput = ''; Widget build(BuildContext context) { return Form( key: _formKey, child: Column( children: <Widget>[ TextFormField( onSaved: (value) { _userInput = value; }, ), ElevatedButton( onPressed: _saveForm, child: Text('Submit'), ), ], ), ); } void _saveForm() { final isValid = _formKey.currentState.validate(); if (isValid) { _formKey.currentState.save(); print("User input value is: $_userInput"); } } }
In this example, _formKey manages the form state, and _userInput stores the user's input. When the user submits the form (after validation), it saves the data and prints the value.
Summary
The choice depends on your specific requirements. For simple input fields, TextEditingController is sufficient. For complex form validation scenarios, it is recommended to use Form with TextFormField.