How to make a custom checkbox FormField in Flutter

In my current project, I need a screen with some input fields which must be validated based on user input. Some fields are mandatory and without filling them the user will not be able to proceed to another screen. For normal input text fields, this is easy to do with the TextFormField widget.

  • TextFormField wraps a TextField widget and integrates it into a FormField widget, which allows us to save, update and validate the field.

But what if we have a radio button or check button? The most correct solution is to create a custom field that extends FormField. How to do this and how to integrate it into the project I will show in this article. So, let's go!

insert image description here
In this article, I'll see how to create a custom checkbox widget. If the user does not agree to the Privacy Policy, he/she cannot complete the registration process. Other types of input fields, such as radio buttons, are done in the same way.

step 1

As I said, first we need to create a custom checkbox that extends the FormField of type bool, since the checkbox is either true or false. To do this, we create a new file called checkbox_form_field_with_error_message.dart and add the following code:

class CheckBoxFormFieldWithErrorMessage extends FormField<bool> {

  final String labelText;
  final bool isChecked;
  String error;
  final void Function(bool?) onChanged;

 CheckBoxFormFi

Guess you like

Origin blog.csdn.net/iCloudEnd/article/details/131268202