CheckboxSuperFormField<T> constructor

CheckboxSuperFormField<T>({
  1. Key? key,
  2. required CheckboxBuilder<T> builder,
  3. required String name,
  4. required List<CheckboxOption<T>> options,
  5. List<SuperFormFieldRule>? rules,
  6. void onChanged(
    1. T value,
    2. bool checked
    )?,
  7. bool? enabled,
})

Creates a CheckboxSuperFormField that delegates its build to a builder while providing helpful CheckboxState abstraction.

You can check listTileCheckboxBuilder as an example implementation used in CheckboxSuperFormField.listTile.

Implementation

CheckboxSuperFormField({
  Key? key,
  required CheckboxBuilder<T> builder,
  required String name,
  required this.options,
  List<SuperFormFieldRule>? rules,
  void Function(T value, bool checked)? onChanged,
  this.enabled,
}) : super(
        key: key,
        name: name,
        rules: rules ?? [],
        builder: (context, fieldState, formState) {
          final List<T> currentValue =
              (fieldState.data?.value as List<T>?) ?? [];

          void effectiveOnChanged(T value, bool checked) {
            List<T> newValue = currentValue;

            if (checked) {
              if (!currentValue.contains(value)) {
                newValue = <T>[...currentValue, value];
              }
            } else {
              newValue = currentValue
                  .where((element) => element != value)
                  .toList(growable: false);
            }

            SuperFormFieldData newData = fieldState.data!.copyWithValue(
              value: newValue,
              touched: true,
            );

            // If the field was tried to be submitted it should be now revalidated every change
            if (formState.validationMode == ValidationMode.onChange ||
                newData.submitted) {
              newData = newData.validate(rules ?? []);
            }

            formState.updateFieldData(newData);

            if (onChanged != null) {
              onChanged(value, checked);
            }
          }

          final effectiveEnabled = enabled ?? formState.enabled;

          return builder(
            context,
            CheckboxState<T>(
              options,
              currentValue,
              effectiveEnabled ? effectiveOnChanged : null,
              fieldState.focusNode,
            ),
          );
        },
      );