实现排序功能
Some checks failed
Dart CI / build (push) Failing after 9s

This commit is contained in:
2026-04-05 19:39:37 +08:00
parent 90f7159746
commit 2bb8a83bbc
9 changed files with 193 additions and 80 deletions

View File

@@ -13,19 +13,17 @@ class PhotoRepository {
PhotoRepository(this.basePath);
/// 获取相册中所有照片(不分页,保留兼容)
Future<List<Photo>> getPhotosByAlbumId(int id) async {
final all = await _loadPhotosForAlbum(id);
return all;
}
/// 获取相册中的照片(分页)
Future<PageResult<Photo>> getPhotosByAlbumIdPaged(
int id, {
int page = 1,
int size = 20,
String sortBy = 'fileName',
String order = 'asc',
}) async {
final all = await _loadPhotosForAlbum(id);
all.sort(_createComparator(sortBy, order));
final total = all.length;
final startIndex = (page - 1) * size;
final endIndex = startIndex + size;
@@ -90,12 +88,55 @@ class PhotoRepository {
});
final photos = await Future.wait(photoFutures);
// 按文件名排序,确保跨平台分页结果一致
photos.sort((a, b) => a.fileName.compareTo(b.fileName));
_map[id] = List.from(photos);
return photos;
}
/// 创建排序比较器
int Function(Photo, Photo) _createComparator(
String sortBy,
String order,
) {
final ascending = order == 'asc';
int compare(Photo a, Photo b) {
// Null always sorts last regardless of ascending/descending
int nullAwareCompare(int? valueA, int? valueB) {
if (valueA == null && valueB == null) return 0;
if (valueA == null) return 1;
if (valueB == null) return -1;
return ascending
? valueA.compareTo(valueB)
: valueB.compareTo(valueA);
}
switch (sortBy) {
case 'fileName':
return ascending
? a.fileName.compareTo(b.fileName)
: b.fileName.compareTo(a.fileName);
case 'fileSize':
return ascending
? a.fileSize.compareTo(b.fileSize)
: b.fileSize.compareTo(a.fileSize);
case 'createdAt':
return ascending
? a.createdAt.compareTo(b.createdAt)
: b.createdAt.compareTo(a.createdAt);
case 'width':
return nullAwareCompare(a.width, b.width);
case 'height':
return nullAwareCompare(a.height, b.height);
default:
return ascending
? a.fileName.compareTo(b.fileName)
: b.fileName.compareTo(a.fileName);
}
}
return compare;
}
Future<Photo?> getPhotoById(int id) async {
try {
return _map.values.expand((l) => l).firstWhere((p) => p.id == id);

View File

@@ -204,10 +204,16 @@ Future<Response> _getPhotosOfAlbumHandler(
final page = int.tryParse(req.url.queryParameters['page'] ?? '1') ?? 1;
final size = int.tryParse(req.url.queryParameters['size'] ?? '20') ?? 20;
// 获取排序参数
final sortBy = req.url.queryParameters['sort'] ?? 'fileName';
final order = req.url.queryParameters['order'] ?? 'asc';
final result = await repo.getPhotosByAlbumIdPaged(
albumId,
page: page,
size: size,
sortBy: sortBy,
order: order,
);
return jsonResponse({