Flutter form get values



Flutter Form Get Values

Flutter Form Get Values

When working with forms in Flutter, you can utilize the Form widget to create a collection of form fields and access their values. Here’s an example:

{% raw %}
import 'package:flutter/material.dart';

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State {
  final _formKey = GlobalKey();
  String _name = '';
  String _email = '';

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            decoration: InputDecoration(labelText: 'Name'),
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter your name';
              }
              return null;
            },
            onSaved: (value) {
              _name = value;
            },
          ),
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter your email';
              }
              return null;
            },
            onSaved: (value) {
              _email = value;
            },
          ),
          RaisedButton(
            onPressed: () {
              if (_formKey.currentState.validate()) {
                _formKey.currentState.save();
                print('Name: $_name');
                print('Email: $_email');
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('Flutter Form'),
      ),
      body: Center(
        child: MyForm(),
      ),
    ),
  ));
}
{% endraw %}

In this example, we create a Form widget using the _formKey global key to manage the form’s state. Inside the form, we have two TextFormFields for capturing the user’s name and email. Both fields have a validation function specified in the validator property, which checks if the fields are empty. The onSaved property is responsible for saving the field value to the respective variables (_name and _email).

Finally, we have a RaisedButton that triggers the form validation and saves the field values when pressed. If the form passes validation, the print function outputs the name and email values.

Remember to include the necessary dependencies in your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter

Leave a comment