submit method

  1. @override
void submit([
  1. Future<void> fn()?
])
override

Submit the form.

The argument is the callback to be invoked. If it is null the callback defined in RM.injectForm.submit will be used.

This is an example of form submission with server validation:

 final form = RM.injectForm(
   submit: () async {
     //This is the default submission logic,
     //It may be override when calling form.submit( () async { });
     //It may contains server validation.
    await serverError =  authRepository.signInWithEmailAndPassword(
       email: email.text,
       password: password.text,
     );
     //after server validation
     if(serverError == 'Invalid-Email'){
       email.error = 'Invalid email';
     }
     if(serverError == 'Weak-Password'){
       email.error = 'Password must have more the 6 characters';
     }
   },
 );

Implementation

@override
void submit([Future<void> Function()? fn]) async {
  if (!validate(true)) {
    return;
  }

  Future<void> setState(Function()? call) async {
    dynamic result = call?.call();
    try {
      if (result is Future) {
        snapValue = snapValue.copyToIsWaiting();
        sideEffects
          ?..onSetState?.call(snapState)
          ..onAfterBuild?.call();
        notify();
        await result;
      }
      snapValue = snapValue.copyToHasData(null);
      sideEffects
        ?..onSetState?.call(snapState)
        ..onAfterBuild?.call();
      if (autoFocusOnFirstError) {
        _BaseFormField? firstErrorField;
        for (var field in _fields) {
          if (field.hasError) {
            firstErrorField = field;
            break;
          }
        }
        if (firstErrorField != null) {
          firstErrorField._focusNode?.requestFocus();
        }
      }
      for (var e in _fields) {
        e
          ..isDirty = false
          .._initialIsDirtyText = e.value;
      }
      notify();
    } catch (e, s) {
      snapValue = snapValue.copyWith(
        status: StateStatus.hasError,
        error: SnapError(
          error: e,
          stackTrace: s,
          refresher: () => submit(fn),
        ),
        infoMessage: '',
      );
      sideEffects
        ?..onSetState?.call(snapState)
        ..onAfterBuild?.call();
      notify();
    }
  }

  await setState(
    () => fn == null ? _submit?.call() : fn(),
  );
}