fetchNext method

Future<List<MessageThread>> fetchNext({
  1. required dynamic onSuccess(
    1. List<MessageThread> threads
    )?,
  2. required dynamic onError(
    1. CometChatException excep
    )?,
})

Fetches the next page of threads.

Resolves [] once the list is exhausted. Rejects with ERR_REQUEST_IN_PROGRESS if a fetch is already in flight on this request.

Implementation

Future<List<MessageThread>> fetchNext(
    {required Function(List<MessageThread> threads)? onSuccess,
    required Function(CometChatException excep)? onError}) async {
  try {
    // Validate before any network call (§5.3).
    if (limit < 1 || limit > maxLimit) {
      final error = CometChatException(
        'ERR_INVALID_LIMIT',
        'Limit must be between 1 and $maxLimit',
        'Limit must be between 1 and $maxLimit',
      );
      if (onError != null) onError(error);
      return [];
    }
    if (guid != null && guid!.isNotEmpty && uid != null && uid!.isNotEmpty) {
      final error = CometChatException(
        'ERR_INVALID_FILTER',
        'setGuid and setUid are mutually exclusive — set only one',
        'setGuid and setUid are mutually exclusive — set only one',
      );
      if (onError != null) onError(error);
      return [];
    }

    if (_exhausted) {
      if (onSuccess != null) onSuccess([]);
      return [];
    }
    if (_inProgress) {
      final error = CometChatException(
        'ERR_REQUEST_IN_PROGRESS',
        'A fetch is already in progress on this ThreadsRequest',
        'A fetch is already in progress on this ThreadsRequest',
      );
      if (onError != null) onError(error);
      return [];
    }

    _inProgress = true;
    try {
      final fresh = await _fetchFreshRows();
      if (onSuccess != null) onSuccess(fresh);
      return fresh;
    } finally {
      _inProgress = false;
    }
  } on sdk_errors.SdkException catch (sdkEx) {
    final cometChatEx = CometChatException(
      sdkEx.code,
      sdkEx.details ?? sdkEx.message,
      sdkEx.message,
    );
    if (onError != null) onError(cometChatEx);
  } catch (e) {
    final cometChatEx = CometChatException(
      ErrorCode.errorUnhandledException,
      e.toString(),
      e.toString(),
    );
    if (onError != null) onError(cometChatEx);
  }
  return [];
}