PaginationResponse<T>.fromJson constructor

PaginationResponse<T>.fromJson(
  1. Map<String, dynamic> json,
  2. T itemFromJson(
    1. Map<String, dynamic>
    ), {
  3. List dataExtractor(
    1. Map<String, dynamic>
    )?,
  4. int totalExtractor(
    1. Map<String, dynamic>
    )?,
  5. int skipExtractor(
    1. Map<String, dynamic>
    )?,
  6. int limitExtractor(
    1. Map<String, dynamic>
    )?,
  7. dynamic nextPageKeyExtractor(
    1. Map<String, dynamic>
    )?,
})

Creates a PaginationResponse from JSON with custom extractors

This factory allows adaptation to different API response formats by providing custom functions to extract data from the JSON response.

Parameters:

  • json: The JSON response from the API
  • itemFromJson: Function to convert each item JSON to type T
  • dataExtractor: Custom function to extract the items array
  • totalExtractor: Custom function to extract total count
  • skipExtractor: Custom function to extract skip/offset value
  • limitExtractor: Custom function to extract limit/page size
  • nextPageKeyExtractor: Custom function to extract next page key

Implementation

factory PaginationResponse.fromJson(
  Map<String, dynamic> json,
  T Function(Map<String, dynamic>) itemFromJson, {
  List<dynamic> Function(Map<String, dynamic>)? dataExtractor,
  int Function(Map<String, dynamic>)? totalExtractor,
  int Function(Map<String, dynamic>)? skipExtractor,
  int Function(Map<String, dynamic>)? limitExtractor,
  dynamic Function(Map<String, dynamic>)? nextPageKeyExtractor,
}) {
  // Default extractors for common API patterns
  final items =
      (dataExtractor?.call(json) ??
              json['data'] ??
              json['items'] ??
              json['results'] ??
              json)
          as List<dynamic>;

  final itemList = items
      .map((item) => itemFromJson(item as Map<String, dynamic>))
      .toList();

  final total =
      totalExtractor?.call(json) ??
      json['total'] ??
      json['totalCount'] ??
      json['count'] ??
      itemList.length;

  final skip =
      skipExtractor?.call(json) ?? json['skip'] ?? json['offset'] ?? 0;

  final limit =
      limitExtractor?.call(json) ??
      json['limit'] ??
      json['pageSize'] ??
      json['size'] ??
      itemList.length;

  final nextPageKey =
      nextPageKeyExtractor?.call(json) ??
      (skip + limit < total ? skip + limit : null);

  return PaginationResponse<T>(
    items: itemList,
    total: total as int,
    skip: skip as int,
    limit: limit as int,
    isLastPage: skip + limit >= total,
    nextPageKey: nextPageKey,
  );
}