tezvyn:

Build Custom Inputs with Flutter's FormField Widget

AI-drafted, machine-checkedSource: api.flutter.devadvanced

FormField is a state wrapper, not a UI widget, that turns any widget into a validatable form input. Use it for custom inputs like sliders or star ratings that must integrate with a Form. The footgun is forgetting to supply the UI via its `builder`.

WHY IT EXISTS Flutter provides TextFormField for text, but forms often need more complex inputs like custom sliders, date pickers, or even signature pads. FormField exists to provide a standard way to manage the state (value, error, dirty status) for any widget, allowing it to integrate seamlessly into a Form.

THE MENTAL MODEL Think of FormField as a headless controller for a form input. It doesn't draw anything on the screen itself. Instead, it holds the value, the validation logic, and the error state, and exposes this state to a UI widget you provide via its builder function. It's the "brain" that makes a simple widget "form-aware".

HOW IT WORKS You instantiate a FormField and provide a builder function. This function receives a FormFieldState object as its argument. Inside the builder, you return the widget you want the user to interact with, like a row of Icons for a star rating. You use the state object to read the current value (state.value), display errors (state.errorText), and update the value when the user interacts with your widget (state.didChange(newValue)). The validator function you provide is called to check the value, and onSaved is called when Form.save() is invoked.

WHEN TO USE IT Use FormField whenever you need a custom input that's not a standard text box. Examples include a slider for a price range, a custom toggle switch with complex state, a star rating selector, or a color picker. It's the correct way to make these custom widgets participate in form-wide validation, saving, and resetting.

WHEN NOT TO USE IT Don't use FormField for simple text input; TextFormField is a pre-built, convenient implementation for that exact purpose. Also, if your input doesn't need to be part of a larger form, doesn't require validation, and its state can be managed locally, using a raw StatefulWidget might be simpler.

ONE CANONICAL EXAMPLE To create a custom boolean switch, the FormField would hold a bool value. Its builder would return a Switch widget. The Switch's value property would be set to state.value, and its onChanged callback would call state.didChange(newValue). This connects the UI of the Switch to the state management of the FormField, making it a submittable part of a Form.

Read the original → api.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.