delegateAsync static method

AsyncValidator delegateAsync(
  1. AsyncValidatorFunction validator, {
  2. int debounceTime = 0,
})

Creates a validator that delegates the validation to the external asynchronous validator function.

The debounceTime argument is the duration in milliseconds to wait before executing the validator after the control's value last changes.

If debounceTime is 0, the validator is executed immediately.

Example:

final form = fb.group({
  'userName': FormControl<String>(
    asyncValidators: [
      Validators.delegateAsync((control) async {
        // Simulate a call to a backend service
        await Future<void>.delayed(Duration(seconds: 1));
        if (control.value == 'existingUser') {
          return {'unique': true};
        }
        return null;
      }, debounceTime: 300),
    ],
  ),
});

You can also use it without a debounce time:

final form = fb.group({
  'userName': FormControl<String>(
    asyncValidators: [
      Validators.delegateAsync((control) async {
        // Simulate a call to a backend service
        await Future<void>.delayed(Duration(seconds: 1));
        if (control.value == 'existingUser') {
          return {'unique': true};
        }
        return null;
      }), // No debounce time
    ],
  ),
});

Implementation

static AsyncValidator<dynamic> delegateAsync(
  AsyncValidatorFunction validator, {
  int debounceTime = 0,
}) {
  final delegateValidator = DelegateAsyncValidator(validator);
  if (debounceTime > 0) {
    return DebouncedAsyncValidator(delegateValidator, debounceTime);
  }
  return delegateValidator;
}