Flutter Form Builder: A Comprehensive Guide for Form Input and Validation in Flutter

Published on by Flutter News Hub

Flutter Form Builder: A Comprehensive Guide for Form Input and Validation in Flutter

Flutter Form Builder is a robust package for building data collection forms in Flutter. It simplifies the process of creating forms, handling validation, and collecting user input by removing the need for boilerplate code.

Features

  • Easy creation of forms with various input types
  • Seamless value extraction from forms
  • Robust validation capabilities for form fields
  • Real-time updates and validation checks
  • Comprehensive support for cross-platform compatibility

Input Types

Flutter Form Builder provides a wide range of input types for creating custom forms. These include:

  • FormBuilderCheckbox: Single checkbox field
  • FormBuilderCheckboxGroup: Multiple checkbox options
  • FormBuilderChoiceChip: Radio button-like chip
  • FormBuilderDateRangePicker: Date range selection
  • FormBuilderDateTimePicker: Date, time, and datetime input
  • FormBuilderDropdown: Dropdown menu for value selection
  • FormBuilderFilterChip: Checkbox-like chip
  • FormBuilderRadioGroup: Radio button group
  • FormBuilderRangeSlider: Slider for selecting a range
  • FormBuilderSlider: Slider for numeric value selection
  • FormBuilderSwitch: On/off switch
  • FormBuilderTextField: Material Design text field

Basic Usage

To use Flutter Form Builder, create a FormBuilder widget as the parent of your form fields. Specify the fields using the appropriate input type. Here's an example:

import 'package:flutter_form_builder/flutter_form_builder.dart';

final _formKey = GlobalKey();

FormBuilder(
  key: _formKey,
  child: Column(
    children: [
      FormBuilderTextField(
        name: 'name',
        decoration: InputDecoration(labelText: 'Name'),
        validator: FormBuilderValidators.required(),
      ),
      FormBuilderDropdown(
        name: 'gender',
        decoration: InputDecoration(labelText: 'Gender'),
        items: ['Male', 'Female', 'Other']
          .map((gender) => FormBuilderFieldOption(value: gender))
          .toList(),
      ),
    ],
  ),
);

Validation

Input fields can be validated using the validator attribute. For example, to ensure a required field:

FormBuilderTextField(
  name: 'name',
  decoration: InputDecoration(labelText: 'Name'),
  validator: FormBuilderValidators.required(),
);

Value Retrieval

Once the form is submitted, use the FormBuilderState to access the form values. Here's an example:

if (_formKey.currentState.validate()) {
  print(_formKey.currentState.value);
}

Specific Use Cases

Conditional Validation

Validate fields based on the values of other fields:

FormBuilderRadioGroup(
  decoration: InputDecoration(labelText: 'Language'),
  name: 'language',
  options: ['English', 'Spanish', 'Other']
    .map((lang) => FormBuilderFieldOption(value: lang))
    .toList(),
),
FormBuilderTextField(
  name: 'other_language',
  decoration: InputDecoration(labelText: 'Other Language'),
  validator: (val) {
    if (_formKey.currentState.fields['language'].value == 'Other' && (val == null || val.isEmpty)) {
      return 'Please specify your other language';
    }
    return null;
  },
);

Custom Field Implementation

Create your own form field by extending FormBuilderField:

class FormBuilderCustomField extends FormBuilderField {
  FormBuilderCustomField({
    required String name,
    required FormFieldValidator validator,
    InputDecoration? decoration,
    T? initialValue,
    ValueChanged? onChanged,
  }) : super(
    name: name,
    initialValue: initialValue,
    validator: validator,
    decoration: decoration,
    onChanged: onChanged,
  );

  @override
  Widget build(FormFieldState field) {
    // Custom form field implementation here
  }
}

Programmatic Field Value Modification

Change field values programmatically:

_formKey.currentState.fields['name'].didChange('new value');

Ecosystem

The Flutter Form Builder ecosystem includes complementary packages for enhanced form functionality:

Conclusion

Flutter Form Builder empowers Flutter developers to create user-friendly and data-driven forms with ease. Its extensive library of input types, robust validation capabilities, and flexible customization options make it an essential tool for building a wide range of form applications in Flutter.

Flutter News Hub