whenOrNull<TResult extends Object?> method

  1. @optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
  1. TResult? withAccessToken(
    1. AuthToken authToken,
    2. String oldPassword,
    3. String newPassword
    )?,
  2. TResult? withFreshAccessToken(
    1. AuthToken freshAuthToken,
    2. String newPassword
    )?,
  3. TResult? withEmail(
    1. String email,
    2. String verificationCode,
    3. String newPassword
    )?,
  4. TResult? withPhoneNumber(
    1. String phoneNumber,
    2. String verificationCode,
    3. String newPassword
    )?,
})

A variant of when that fallback to returning null

It is equivalent to doing:

switch (sealedClass) {
  case Subclass(:final field):
    return ...;
  case _:
    return null;
}

Implementation

@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
  TResult? Function(
          AuthToken authToken, String oldPassword, String newPassword)?
      withAccessToken,
  TResult? Function(AuthToken freshAuthToken, String newPassword)?
      withFreshAccessToken,
  TResult? Function(
          String email, String verificationCode, String newPassword)?
      withEmail,
  TResult? Function(
          String phoneNumber, String verificationCode, String newPassword)?
      withPhoneNumber,
}) {
  final _that = this;
  switch (_that) {
    case UpdatePasswordRequestWithAccessToken() when withAccessToken != null:
      return withAccessToken(
          _that.authToken, _that.oldPassword, _that.newPassword);
    case UpdatePasswordRequestWithFreshAccessToken()
        when withFreshAccessToken != null:
      return withFreshAccessToken(_that.freshAuthToken, _that.newPassword);
    case UpdatePasswordRequestWithEmail() when withEmail != null:
      return withEmail(
          _that.email, _that.verificationCode, _that.newPassword);
    case UpdatePasswordRequestWithPhoneNumber() when withPhoneNumber != null:
      return withPhoneNumber(
          _that.phoneNumber, _that.verificationCode, _that.newPassword);
    case _:
      return null;
  }
}