Flutter formstate get values

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 assigned to the _formKey variable.

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.

Leave a comment