PaginationResponse<T>.fromJson constructor
PaginationResponse<T>.fromJson (})
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 APIitemFromJson
: Function to convert each item JSON to type TdataExtractor
: Custom function to extract the items arraytotalExtractor
: Custom function to extract total countskipExtractor
: Custom function to extract skip/offset valuelimitExtractor
: Custom function to extract limit/page sizenextPageKeyExtractor
: 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,
);
}