flutter_form_builder 7.0.0-alpha.2
flutter_form_builder: ^7.0.0-alpha.2 copied to clipboard

This package helps in creation of forms in Flutter by removing the boilerplate code, reusing validation, react to changes, and collect final user input.

Flutter FormBuilder - flutter_form_builder #

This package helps in creation of data collection forms in Flutter by removing the boilerplate needed to build a form, validate fields, react to changes, and collect final user input.


Pub Version GitHub Workflow Status Codecov CodeFactor Grade GitHub OSS Lifecycle

Buy me a coffee


Example #

final _formKey = GlobalKey<FormBuilderState>();

@override
Widget build(BuildContext context) {
  return Column(
    children: <Widget>[
      FormBuilder(
        key: _formKey,
        autovalidate: true,
        child: Column(
          children: <Widget>[
            
          ],
        ),
      ),
      Row(
        children: <Widget>[
          Expanded(
            child: MaterialButton(
              color: Theme.of(context).accentColor,
              child: Text(
                "Submit",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                _formKey.currentState.save();
                if (_formKey.currentState.validate()) {
                  print(_formKey.currentState.value);
                } else {
                  print("validation failed");
                }
              },
            ),
          ),
          SizedBox(width: 20),
          Expanded(
            child: MaterialButton(
              color: Theme.of(context).accentColor,
              child: Text(
                "Reset",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                _formKey.currentState.reset();
              },
            ),
          ),
        ],
      ),
    ],
  );
}

FormBuilderField attributes #

In order to create an input field in the form, along with the label, and any applicable validation, there are several attributes that are supported by all types of inputs namely:

AttributeTypeDefaultRequiredDescription
nameStringYesThis will form the key in the form value Map
initialValueTnullNoThe initial value of the input field
enabledbooltrueNoDetermines whether the field widget will accept user input.
decorationInputDecorationInputDecoration()NoDefines the border, labels, icons, and styles used to decorate the field.
validatorFormFieldValidator<T>nullNoA FormFieldValidator that will check the validity of value in the FormField
onChangedValueChanged<T>nullNoThis event function will fire immediately the the field value changes
valueTransformerValueTransformer<T>nullNoFunction that transforms field value before saving to form value. e.g. transform TextField value for numeric field from String to num
The rest of the attributes will be determined by the type of Widget being used.

Building your own custom field #

To build your own field within a FormBuilder, we use FormBuilderField which will require that you define your own field.

var options = ["Option 1", "Option 2", "Option 3"];
FormBuilderField(
  name: "name",
  validator: FormBuilderValidators.compose([
    FormBuilderValidators.required(context),
  ]),
  builder: (FormFieldState<dynamic> field) {
    return InputDecorator(
      decoration: InputDecoration(
        labelText: "Select option",
        contentPadding:
            EdgeInsets.only(top: 10.0, bottom: 0.0),
        border: InputBorder.none,
        errorText: field.errorText,
      ),
      child: Container(
        height: 200,
        child: CupertinoPicker(
          itemExtent: 30,
          children: options.map((c) => Text(c)).toList(),
          onSelectedItemChanged: (index) {
            field.didChange(options[index]);
          },
        ),
      ),
    );
  },
),

Programmatically changing field value #

You can either change the value of one field at a time like so:

_formKey.currentState.fields['color_picker'].didChange(Colors.black);

Or multiple fields value like so:

_formKey.currentState.patchValue({
  'age': '50',
  'slider': 6.7,
  'filter_chip': ['Test 1'],
  'choice_chip': 'Test 2',
  'rate': 4,
  'chips_test': [
    Contact('Andrew', 'stock@man.com', 'https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX4057996.jpg'),
  ],
});

Programmatically inducing an error #

Declare a variable to hold your error:

String _emailError;

Use the variable as the errorText within InputDecoration

FormBuilderTextField(
  name: 'email',
  decoration: InputDecoration(
    labelText: 'Email',
    errorText: _emailError,
  ),
  validator: FormBuilderValidators.compose([
      FormBuilderValidators.required(context),
      FormBuilderValidators.email(context),
  ]),
),

Set the error text

RaisedButton(
  child: Text('Submit'),
  onPressed: () async {
    setState(() => _emailError = null);
    if(checkIfEmailExists()){
      setState(() => _emailError = 'Email already taken.');
    }
  },
),

Conditional validation #

You can also validate a field based on the value of another field

FormBuilderRadioGroup(
  decoration: InputDecoration(labelText: 'My best language'),
  name: 'my_language',
  validator: FormBuilderValidators.required(context),
  options: [
    'Dart',
    'Kotlin',
    'Java',
    'Swift',
    'Objective-C',
    'Other'
  ]
    .map((lang) => FormBuilderFieldOption(value: lang))
    .toList(growable: false),
  ),
  FormBuilderTextField(
    name: 'specify',
    decoration:
        InputDecoration(labelText: 'If Other, please specify'),
    validator: (val) {
      if (_formKey.currentState.fields['my_language']?.value ==
              'Other' &&
          (val == null || val.isEmpty)) {
        return 'Kindly specify your language';
      }
      return null;
    },
  ),

Additional input fields #

To make this package compartible with as many platforms as Flutter supports, we separated some input fields into their own packages because they depend on platform-specific plugins. Here's are the links to some of the packages that could be used with FormBuilder

Support #

Issues and PRs #

Any kind of support in the form of reporting bugs, answering questions or PRs is always appreciated.

Coffee :-) #

If this package was helpful to you in delivering your project or you just wanna to support this package, a cup of coffee would be highly appreciated ;-)

Buy me a coffee

876
likes
130
pub points
97%
popularity

Publisher

danvickmiller.dev

This package helps in creation of forms in Flutter by removing the boilerplate code, reusing validation, react to changes, and collect final user input.

Repository (GitHub)
View/report issues

Documentation

API reference

License

MIT (LICENSE)

Dependencies

flutter

More

Packages that depend on flutter_form_builder