0
0
Fluttermobile~5 mins

Form submission in Flutter

Choose your learning style9 modes available
Introduction

Forms let users enter information in your app. Submitting a form sends that information to be used or saved.

When a user needs to sign up or log in.
When collecting feedback or survey answers.
When entering details like address or payment info.
When searching with filters or criteria.
When sending messages or comments.
Syntax
Flutter
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter some text';
          }
          return null;
        },
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // Process data
          }
        },
        child: Text('Submit'),
      ),
    ],
  ),
);

Use a GlobalKey to manage the form state.

Call _formKey.currentState!.validate() to check if all fields are valid before submitting.

Examples
A simple form with one text field and a validator that checks if the field is empty.
Flutter
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: TextFormField(
    validator: (value) => value!.isEmpty ? 'Enter text' : null,
  ),
);
Button that checks form validity and prints a message when pressed.
Flutter
ElevatedButton(
  onPressed: () {
    if (_formKey.currentState!.validate()) {
      print('Form is valid');
    }
  },
  child: Text('Submit'),
);
Sample App

This app shows a form with one text field for the user's name. When the user taps Submit, it checks if the field is not empty. If valid, it shows a message greeting the user.

Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Form Submission Example')),
        body: const Padding(
          padding: EdgeInsets.all(16),
          child: MyForm(),
        ),
      ),
    );
  }
}

class MyForm extends StatefulWidget {
  const MyForm({super.key});

  @override
  State<MyForm> createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  final _formKey = GlobalKey<FormState>();
  final _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _submit() {
    if (_formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Hello, ${_controller.text}!')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            controller: _controller,
            decoration: const InputDecoration(
              labelText: 'Enter your name',
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your name';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _submit,
            child: const Text('Submit'),
          ),
        ],
      ),
    );
  }
}
OutputSuccess
Important Notes

Always dispose of controllers to free resources.

Use ScaffoldMessenger to show messages after submission.

Validators help ensure users enter correct data before submitting.

Summary

Forms collect user input and need validation before submission.

Use a GlobalKey<FormState> to manage form state.

Show feedback to users after they submit the form.