register method

SuperFormFieldData register({
  1. required String name,
  2. required List<SuperFormFieldRule> rules,
  3. SuperFormFieldState? fieldState,
})

Registers the field for a given name with a set of rules.

This field is usually called by SuperFormFields like TextSuperFormField, but it is totally fine to call this method manually to register a field that doesn't have a controlling widget.

If the field of given name is already registered then nothing changes and existing SuperFormFieldData is returned.

Implementation

SuperFormFieldData register({
  required String name,
  required List<SuperFormFieldRule> rules,
  SuperFormFieldState? fieldState,
}) {
  assert(name.isNotEmpty, "Field name cannot be empty");
  final SuperFormFieldData? existingFieldData = _fieldsData[name];

  if (fieldState != null && !_fields.contains(fieldState)) {
    _fields.add(fieldState);
  }

  if (existingFieldData == null) {
    // Update internal copy of initial values
    _initialValues[name] = widget.initialValues[name];

    final newField = SuperFormFieldData(
      name: name,
      value: _restorableFormValues.value[name] ?? _initialValues[name],
      errors: const [],
      submitted: false,
      touched: false,
    );
    _fieldsData = {..._fieldsData, name: newField};
    _fieldsRules = {..._fieldsRules, name: rules};

    _triggerRebuild();
    widget.onChange(data);
    return newField;
  } else {
    return existingFieldData;
  }
}