eskemaList<T> function

IValidator eskemaList<T>(
  1. List<IValidator> eskema
)

Returns a Validator that checks a value against the eskema provided, the eskema defines a validator for each item in the list

Example:

final isValidList = eskemaList([isType<String>(), isType<int>()]);
isValidList(["1", 2]).isValid;   // true
isValidList(["1", "2"]).isValid; // false
isValidList([1, "2"]).isValid;   // false

isValidList will only be valid:

  • if the array is of length 2
  • the first item is a string
  • and the second item is an int

This validator also checks that the value is a list

Implementation

IValidator eskemaList<T>(List<IValidator> eskema) {
  FutureOr<Result> listPredicate(value) {
    final errors = <Expectation>[];

    FutureOr<Result> loop(int index) {
      if (index >= value.length) {
        return errors.isEmpty
            ? Result.valid(value)
            : Result.invalid(value, expectations: errors);
      }

      final item = value[index];
      final effectiveValidator = eskema[index];

      // Nullable short-circuit
      if (item == null && effectiveValidator.isNullable) {
        return loop(index + 1);
      }

      final res = effectiveValidator.validator(item);

      if (res is Future<Result>) {
        return res.then((r) {
          _collectListIndex(r, errors, index, null);
          return loop(index + 1);
        });
      }

      _collectListIndex(res, errors, index, null);

      return loop(index + 1);
    }

    return loop(0);
  }

  return isType<List>() & listIsOfLength(eskema.length) & Validator(listPredicate);
}