乐闻世界logo
搜索文章和话题

How to get the TextField value in flutter

1个答案

1

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:

  1. Define TextEditingController First, create an instance of TextEditingController within your StatefulWidget and ensure proper disposal.

    dart
    class 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, ), ); } }
  2. Retrieve the TextField value You can access the current value of the TextField at any time using _controller.text.

    dart
    void _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.

  1. Using Form and TextFormField Create a Form and embed TextFormField within it. Provide an onSaved callback to capture the value when the form is saved.

    dart
    class 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.

2024年8月8日 00:31 回复

你的答案