CheckboxSuperFormField<T> constructor
CheckboxSuperFormField<T> ({
- Key? key,
- required CheckboxBuilder<
T> builder, - required String name,
- required List<
CheckboxOption< options,T> > - List<
SuperFormFieldRule> ? rules, - void onChanged(
- T value,
- bool checked
- 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,
),
);
},
);