To retrieve the values from a Flutter FormState, you can use the getValue method available on the individual fields. First, you need to obtain the FormState object by accessing it via a GlobalKey assigned to the Form widget. Here’s an example:
import 'package:flutter/material.dart'; class MyForm extends StatefulWidget { @override _MyFormState createState() => _MyFormState(); } class _MyFormState extends State{ final _formKey = GlobalKey (); final _nameController = TextEditingController(); final _emailController = TextEditingController(); void _submitForm() { if (_formKey.currentState.validate()) { String name = _nameController.value.text; String email = _emailController.value.text; // Do something with the values... } } @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( children: [ TextFormField( controller: _nameController, validator: (value) { if (value.isEmpty) { return 'Please enter your name'; } return null; // Input is valid }, ), TextFormField( controller: _emailController, validator: (value) { if (value.isEmpty) { return 'Please enter your email address'; } return null; // Input is valid }, ), RaisedButton( onPressed: _submitForm, child: Text('Submit'), ), ], ), ); } } // Usage MyForm(),
In this example, we have a simple form with two TextFormField widgets for name and email input fields. The form is wrapped inside a GlobalKey
Inside the _submitForm function, we validate the form using _formKey.currentState.validate(). If the validation passes, we access the field values using the controller’s value property, and store them in separate variables (name and email in this case). You can perform any actions with these values, such as sending them to an API, saving to a database, or displaying them in a toast message.
Remember to dispose of the TextEditingController objects properly to prevent memory leaks, typically in the dispose method of the State class.
- Flutter expansiontile remove border
- Flutter floating action button position fixed
- Display nested JSON data in HTML table using JavaScript dynamically
- Flutter firstwhereornull
- Flutter firebase delete user
- Flutter failed to delete a directory at “build”. the flutter tool cannot access the file or directory. please ensure that the sdk and/or project is installed in a location that has read/write permissions for the current user.
- Flutter formkey currentstate null