feat(app): 客户端展示多语言并支持筛选分页

This commit is contained in:
Zhou Weidong committed 2026-10-24 17:20:24 +08:00
1 parent 8481611372
commit 8b50b5bd06
68 files changed
+2742 -1120

No files matched your search

+2 -2
View File
@@ -181,7 +181,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
).showSnackBar(SnackBar(content: Text(l10n.authCodeSent)));
_codeFocus.requestFocus();
} on ApiException catch (error) {
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
failureMessage = error.message;
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
@@ -229,7 +229,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
}
if (mounted) Navigator.of(context).pop(true);
} on ApiException catch (error) {
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
failureMessage = error.message;
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
+17 -180
View File
@@ -23,30 +23,18 @@ import '../../core/widgets/catalog_debug_info.dart';
import '../../core/widgets/catalog_endpoint_editor.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../filter/filter_page.dart';
import '../new_releases/new_releases_page.dart';
import '../player/open_player.dart';
import '../ranking/ranking_page.dart';
import '../reserve/reserve_page.dart';
import 'discover_binding.dart';
import 'discover_logic.dart';
import 'discover_types.dart';
import 'widgets/discover_category_tab.dart';
import 'widgets/discover_header.dart';
import 'widgets/discover_search_results.dart';
import 'widgets/discover_toolbar.dart';
import 'widgets/drama_grid.dart';
const Color _filterIconColor = AppColors.blueSoft;
const Color _newIconColor = AppColors.blueSoft;
const double _toolbarHeight = 36;
const double _toolbarGap = 10;
const double _toolbarRadius = 10;
const double _categoryTabHeight = 44;
const double _categoryTabGap = 20;
const double _categorySelectedFontSize = 16;
const double _categoryFontSize = 15;
const double _categoryUnderlineWidth = 20;
const double _categoryUnderlineHeight = 3;
const double _categoryUnderlineStrokeWidth = 2;
const double _stickyHeaderHeight = 44;
const Duration _stickyHeaderTransition = Duration(milliseconds: 160);
const Duration _categoryScrollDuration = Duration(milliseconds: 200);
@@ -295,7 +283,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
List<Widget> _theaterBlocks(AppLocalizations l10n) {
final dramas = theater.dramas;
return [
_toolbar(l10n),
_toolbar(),
if (dramas.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
@@ -318,6 +306,16 @@ class _DiscoverPageState extends State<DiscoverPage> {
child: CircularProgressIndicator(strokeWidth: 2),
),
),
)
else if (dramas.isNotEmpty && !theater.hasMore)
Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
),
];
}
@@ -335,8 +333,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_categoryTab(
key: const Key('theater-category-all'),
DiscoverCategoryTab(
anchorKey: _anchorFor('all'),
id: 'all',
label: l10n.all,
@@ -345,8 +342,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
),
for (final category in categories.categories) ...[
const SizedBox(width: _categoryTabGap),
_categoryTab(
key: Key('theater-category-${category.id}'),
DiscoverCategoryTab(
anchorKey: _anchorFor(category.id),
id: category.id,
label: category.name,
@@ -360,52 +356,6 @@ class _DiscoverPageState extends State<DiscoverPage> {
);
}
Widget _categoryTab({
required Key key,
required GlobalKey anchorKey,
required String id,
required String label,
required bool selected,
required VoidCallback onTap,
}) {
return KeyedSubtree(
key: anchorKey,
child: GestureDetector(
key: key,
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
label,
maxLines: 1,
style: TextStyle(
color: selected ? AppColors.onSurface : AppColors.muted,
fontSize: selected
? _categorySelectedFontSize
: _categoryFontSize,
fontWeight: selected ? FontWeight.w800 : FontWeight.w500,
),
),
const SizedBox(height: 4),
CustomPaint(
key: Key('theater-category-underline-$id'),
size: const Size(
_categoryUnderlineWidth,
_categoryUnderlineHeight,
),
painter: CategoryUnderlinePainter(
color: selected ? AppColors.blue : AppColors.transparent,
),
),
],
),
),
);
}
GlobalKey _anchorFor(String id) {
return _categoryAnchors.putIfAbsent(id, GlobalKey.new);
}
@@ -444,97 +394,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
return true;
}
Widget _toolbar(AppLocalizations l10n) {
return Padding(
padding: const EdgeInsets.fromLTRB(14, 2, 14, 12),
child: Row(
children: [
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-filter'),
icon: Icons.tune_rounded,
color: _filterIconColor,
label: l10n.filter,
onTap: () => _openPage(context, const FilterPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-ranking'),
icon: Icons.local_fire_department_rounded,
color: AppColors.blue,
label: l10n.rankingTab,
onTap: () => _openPage(context, const RankingPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-new'),
icon: Icons.play_circle_fill_rounded,
color: _newIconColor,
label: l10n.newDramas,
onTap: () => _openPage(context, const NewReleasesPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-reserve'),
icon: Icons.calendar_month_rounded,
color: AppColors.blue,
label: l10n.reserve,
onTap: () => _openPage(context, const ReservePage()),
),
),
],
),
);
}
Widget _toolButton({
required Key key,
required IconData icon,
required Color color,
required String label,
required VoidCallback onTap,
}) {
return Material(
color: AppColors.card,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: InkWell(
key: key,
onTap: onTap,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: Container(
height: _toolbarHeight,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(_toolbarRadius),
border: Border.all(color: AppColors.border),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 4),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.onSurface,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
);
Widget _toolbar() {
return DiscoverToolbar(onOpen: (page) => _openPage(context, page));
}
void _openPage(BuildContext context, Widget page) {
@@ -601,27 +462,3 @@ class _DiscoverPageState extends State<DiscoverPage> {
AppRootTab.mine => DiscoverPageAction.mine,
};
}
/// 分类 tab 的弧形选中线。
class CategoryUnderlinePainter extends CustomPainter {
const CategoryUnderlinePainter({required this.color});
final Color color;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = _categoryUnderlineStrokeWidth
..strokeCap = StrokeCap.round;
final path = Path()
..moveTo(1, 1)
..quadraticBezierTo(size.width / 2, size.height + 1, size.width - 1, 1);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CategoryUnderlinePainter oldDelegate) =>
color != oldDelegate.color;
}
@@ -0,0 +1,89 @@
// Author: fruit.com.cn
// 剧场顶部分类标签和选中下划线。
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
const double _selectedFontSize = 16;
const double _fontSize = 15;
const double _underlineWidth = 20;
const double _underlineHeight = 3;
const double _underlineStrokeWidth = 2;
/// 一个可横向滚动的分类标签。
class DiscoverCategoryTab extends StatelessWidget {
const DiscoverCategoryTab({
super.key,
required this.id,
required this.anchorKey,
required this.label,
required this.selected,
required this.onTap,
});
final String id;
final GlobalKey anchorKey;
final String label;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return KeyedSubtree(
key: anchorKey,
child: GestureDetector(
key: Key('theater-category-$id'),
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
label,
maxLines: 1,
style: TextStyle(
color: selected ? AppColors.onSurface : AppColors.muted,
fontSize: selected ? _selectedFontSize : _fontSize,
fontWeight: selected ? FontWeight.w800 : FontWeight.w500,
),
),
const SizedBox(height: 4),
CustomPaint(
key: Key('theater-category-underline-$id'),
size: const Size(_underlineWidth, _underlineHeight),
painter: CategoryUnderlinePainter(
color: selected ? AppColors.blue : AppColors.transparent,
),
),
],
),
),
);
}
}
/// 分类 tab 的弧形选中线。
class CategoryUnderlinePainter extends CustomPainter {
const CategoryUnderlinePainter({required this.color});
final Color color;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = _underlineStrokeWidth
..strokeCap = StrokeCap.round;
final path = Path()
..moveTo(1, 1)
..quadraticBezierTo(size.width / 2, size.height + 1, size.width - 1, 1);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CategoryUnderlinePainter oldDelegate) =>
color != oldDelegate.color;
}
@@ -0,0 +1,119 @@
// Author: fruit.com.cn
// 剧场页筛选、排行、新剧、预约四个入口。
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import '../../filter/filter_page.dart';
import '../../new_releases/new_releases_page.dart';
import '../../ranking/ranking_page.dart';
import '../../reserve/reserve_page.dart';
const double _toolbarHeight = 36;
const double _toolbarGap = 10;
const double _toolbarRadius = 10;
const Color _filterIconColor = AppColors.blueSoft;
const Color _newIconColor = AppColors.blueSoft;
/// 剧场工具条。点按后由调用方打开对应页面。
class DiscoverToolbar extends StatelessWidget {
const DiscoverToolbar({super.key, required this.onOpen});
final void Function(Widget page) onOpen;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.fromLTRB(14, 2, 14, 12),
child: Row(
children: [
Expanded(
child: _button(
key: const Key('theater-toolbar-filter'),
icon: Icons.tune_rounded,
color: _filterIconColor,
label: l10n.filter,
onTap: () => onOpen(const FilterPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _button(
key: const Key('theater-toolbar-ranking'),
icon: Icons.local_fire_department_rounded,
color: AppColors.blue,
label: l10n.rankingTab,
onTap: () => onOpen(const RankingPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _button(
key: const Key('theater-toolbar-new'),
icon: Icons.play_circle_fill_rounded,
color: _newIconColor,
label: l10n.newDramas,
onTap: () => onOpen(const NewReleasesPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _button(
key: const Key('theater-toolbar-reserve'),
icon: Icons.calendar_month_rounded,
color: AppColors.blue,
label: l10n.reserve,
onTap: () => onOpen(const ReservePage()),
),
),
],
),
);
}
Widget _button({
required Key key,
required IconData icon,
required Color color,
required String label,
required VoidCallback onTap,
}) {
return Material(
color: AppColors.card,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: InkWell(
key: key,
onTap: onTap,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: Container(
height: _toolbarHeight,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(_toolbarRadius),
border: Border.all(color: AppColors.border),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 4),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.onSurface,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
);
}
}
+9 -7
View File
@@ -96,9 +96,9 @@ class DramaGridCard extends StatelessWidget {
children: [
_cover(),
const SizedBox(height: _titleGap),
_title(),
_title(context),
const SizedBox(height: _tagsGap),
_tags(),
_tags(context),
],
),
);
@@ -151,9 +151,9 @@ class DramaGridCard extends StatelessWidget {
);
}
Widget _title() {
Widget _title(BuildContext context) {
return Text(
drama.title,
drama.localizedTitle(Localizations.localeOf(context).languageCode),
key: Key('home-drama-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -166,8 +166,8 @@ class DramaGridCard extends StatelessWidget {
);
}
Widget _tags() {
final tags = _tagValues();
Widget _tags(BuildContext context) {
final tags = _tagValues(context);
if (tags.isEmpty) return const SizedBox.shrink();
return Wrap(
spacing: 6,
@@ -193,7 +193,9 @@ class DramaGridCard extends StatelessWidget {
);
}
List<String> _tagValues() {
List<String> _tagValues(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
final result = <String>[];
for (final value in [drama.genre, drama.category]) {
for (final part in value.split(_tagSplitter)) {
@@ -16,7 +16,7 @@ class SearchResultCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final tags = _tags();
final tags = _tags(context);
return Material(
key: Key('search-result-card-${drama.id}'),
color: AppColors.transparent,
@@ -60,7 +60,7 @@ class SearchResultCard extends StatelessWidget {
),
const SizedBox(height: AppDimens.searchResultTitleGap),
Text(
drama.title,
drama.localizedTitle(Localizations.localeOf(context).languageCode),
key: Key('search-result-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -92,7 +92,9 @@ class SearchResultCard extends StatelessWidget {
);
}
List<String> _tags() {
List<String> _tags(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(RegExp(r'[,/、·]')))
+13 -8
View File
@@ -163,8 +163,8 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
synopsis: localizedDramaSynopsis(l10n, drama),
),
),
if (_tagValues(drama).isNotEmpty)
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(drama))),
if (_tagValues(context, drama).isNotEmpty)
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(context, drama))),
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
@@ -442,13 +442,18 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
return record.fraction;
}
List<String> _tagValues(Drama drama) {
List<String> _tagValues(BuildContext context, Drama drama) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
final result = <String>[];
for (final source in [drama.category, drama.genre]) {
for (final part in source.split(_tagSplitter)) {
final value = part.trim();
if (value.isNotEmpty && !result.contains(value)) result.add(value);
if (result.length == _maxTags) return result;
if (localized.isNotEmpty) {
result.addAll(localized.take(_maxTags));
} else {
for (final source in [drama.category, drama.genre]) {
for (final part in source.split(_tagSplitter)) {
final value = part.trim();
if (value.isNotEmpty && !result.contains(value)) result.add(value);
if (result.length == _maxTags) return result;
}
}
}
final language = drama.language.trim();
+9 -4
View File
@@ -176,6 +176,8 @@ class _FavoritesBody extends StatelessWidget {
],
PagedListFooter(
loading: favorites.loadingMore,
hasMore: favorites.hasMore,
hasItems: favorites.cards.isNotEmpty,
errorMessage: favorites.loadMoreError == null
? null
: errorText(l10n, favorites.loadMoreError, l10n.favoritesError),
@@ -265,8 +267,9 @@ class _FavoriteCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final tags = _tags();
final synopsis = drama.synopsis.trim();
final languageCode = Localizations.localeOf(context).languageCode;
final tags = _tags(languageCode);
final synopsis = drama.localizedSynopsis(languageCode).trim();
return Container(
key: ValueKey('favorite-card-${drama.id}'),
decoration: BoxDecoration(
@@ -309,7 +312,7 @@ class _FavoriteCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
drama.title,
drama.localizedTitle(languageCode),
key: ValueKey('favorite-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -444,7 +447,9 @@ class _FavoriteCard extends StatelessWidget {
);
}
List<String> _tags() {
List<String> _tags(String languageCode) {
final localized = drama.localizedTypeLabels(languageCode);
if (localized.isNotEmpty) return localized.take(_maxTags).toList();
final values = <String>[];
for (final source in [drama.genre, drama.category]) {
for (final part in source.split(_tagSplitter)) {
@@ -97,7 +97,7 @@ class FollowingFavoritesGrid extends StatelessWidget {
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
return FollowingGridCard(
dramaId: drama.id,
title: drama.title,
title: drama.localizedTitle(Localizations.localeOf(context).languageCode),
posterUrl: drama.posterUrl,
viewCount: drama.viewCount,
editing: isEditing,
+12 -5
View File
@@ -402,7 +402,11 @@ class _HistoryList extends StatelessWidget {
return FollowingHistoryCard(
dramaId: record.dramaId,
title: _historyTitle(l10n, record),
title: _historyTitle(
l10n,
record,
Localizations.localeOf(context).languageCode,
),
posterUrl: record.displayCover,
viewCount:
record.progress.viewCount ??
@@ -433,10 +437,13 @@ class _HistoryList extends StatelessWidget {
}
}
String _historyTitle(AppLocalizations l10n, WatchRecord record) {
return record.displayTitle.isEmpty
? l10n.episodeLabel(record.episodeNumber)
: record.displayTitle;
String _historyTitle(
AppLocalizations l10n,
WatchRecord record,
String languageCode,
) {
final title = record.localizedDisplayTitle(languageCode);
return title.isEmpty ? l10n.episodeLabel(record.episodeNumber) : title;
}
String _historySubtitle(AppLocalizations l10n, WatchRecord record) {
@@ -130,6 +130,8 @@ class FollowingPagedGrid extends StatelessWidget {
SliverToBoxAdapter(
child: PagedListFooter(
loading: loadingMore,
hasMore: hasMore,
hasItems: hasItems,
errorMessage: loadMoreError,
onRetry: onLoadMore,
),
+10
View File
@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../core/config/app_config.dart';
import '../../core/data/remote/catalog_api.dart';
import '../../core/data/services/home_feed_controller.dart';
import '../../core/data/services/catalog_controller.dart';
import '../../core/data/services/category_controller.dart';
@@ -209,6 +210,7 @@ class _HomeTabsState extends State<_HomeTabs> {
Widget _recommend(BuildContext context) {
return RecommendPage(
feedController: widget.feedController,
catalogApi: _catalogApi(context),
active: logic.tab == 1,
videoOnly: logic.videoImmersive,
onImmersiveChanged: logic.onImmersiveChanged,
@@ -216,6 +218,14 @@ class _HomeTabsState extends State<_HomeTabs> {
);
}
CatalogApi? _catalogApi(BuildContext context) {
try {
return context.read<CatalogApi>();
} on ProviderNotFoundException {
return null;
}
}
void _openSearch(BuildContext context) {
Navigator.of(
context,
@@ -0,0 +1,178 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/services/category_controller.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/drama_grid_skeleton.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../l10n/app_localizations.dart';
import 'home_feed_card.dart';
const double _loadMoreThreshold = 240;
/// 首页分类下的短剧:按分类分页,滑到底加载下一页。
class HomeCategoryDramas extends StatefulWidget {
const HomeCategoryDramas({
super.key,
required this.onOpenDrama,
this.lockedCategoryId,
});
final ValueChanged<Drama> onOpenDrama;
final String? lockedCategoryId;
@override
State<HomeCategoryDramas> createState() => _HomeCategoryDramasState();
}
class _HomeCategoryDramasState extends State<HomeCategoryDramas> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _ensureOpened());
}
@override
void didUpdateWidget(HomeCategoryDramas oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.lockedCategoryId != widget.lockedCategoryId) {
_ensureOpened();
}
}
void _ensureOpened() {
if (!mounted) return;
final controller = context.read<CategoryController>();
final locked = widget.lockedCategoryId;
if (locked == null || locked.isEmpty) return;
final slot = controller.slotOf(locked);
if (slot.loading || slot.pageIndex > 0) return;
unawaited(controller.openCategory(locked));
}
bool _onScroll(ScrollNotification notification) {
final categoryId = widget.lockedCategoryId;
if (categoryId == null || categoryId.isEmpty) return false;
if (notification.depth != 0) return false;
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification &&
notification is! OverscrollNotification) {
return false;
}
unawaited(context.read<CategoryController>().loadMore(categoryId));
return false;
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final controller = context.watch<CategoryController>();
final categoryId = widget.lockedCategoryId ?? '';
final slot = categoryId.isEmpty ? null : controller.slotOf(categoryId);
final dramas = slot?.dramas ?? const <Drama>[];
return Column(
children: [
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
onRefresh: () async {
if (categoryId.isNotEmpty) {
await controller.openCategory(categoryId);
}
},
child: _body(context, l10n, controller, categoryId, dramas),
),
),
),
],
);
}
Widget _body(
BuildContext context,
AppLocalizations l10n,
CategoryController controller,
String categoryId,
List<Drama> dramas,
) {
final slot = categoryId.isEmpty ? null : controller.slotOf(categoryId);
if (slot != null && slot.loading && dramas.isEmpty) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
columns: 3,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
if (dramas.isEmpty) {
return EmptyState(
key: const Key('home-grid-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
);
}
return LayoutBuilder(
builder: (context, constraints) {
final itemWidth =
(constraints.maxWidth -
AppDimens.feedPageHorizontal * 2 -
AppDimens.homeGridGap * 2) /
3;
final itemExtent =
itemWidth / AppDimens.cardCoverAspectRatio +
AppDimens.homeCardBodyExtent;
return CustomScrollView(
key: const Key('home-grid-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
SliverPadding(
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.feedPageHorizontal,
),
sliver: SliverGrid(
key: const Key('home-grid-cards'),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => widget.onOpenDrama(dramas[index]),
),
childCount: dramas.length,
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
child: PagedListFooter(
loading: slot != null && slot.loadingMore,
hasMore: slot?.hasMore ?? false,
hasItems: dramas.isNotEmpty,
errorMessage: null,
onRetry: () => context.read<CategoryController>().loadMore(
categoryId,
),
),
),
),
],
);
},
);
}
}
+9 -6
View File
@@ -99,9 +99,9 @@ class HomeDramaCard extends StatelessWidget {
children: [
_cover(),
const SizedBox(height: _coverTitleGap),
_title(),
_title(context),
const SizedBox(height: _lineGap),
_genre(),
_genre(context),
const SizedBox(height: _lineGap),
_metadata(),
],
@@ -211,9 +211,9 @@ class HomeDramaCard extends StatelessWidget {
);
}
Widget _title() {
Widget _title(BuildContext context) {
return Text(
drama.title,
drama.localizedTitle(Localizations.localeOf(context).languageCode),
key: Key('home-drama-title-${drama.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -225,8 +225,11 @@ class HomeDramaCard extends StatelessWidget {
);
}
Widget _genre() {
final genre = drama.genre.isEmpty ? drama.category : drama.genre;
Widget _genre(BuildContext context) {
final labels = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
final genre = labels.isEmpty
? (drama.genre.isEmpty ? drama.category : drama.genre)
: labels.join(' / ');
return Text(
genre.isEmpty ? l10n.videoPending : genre,
key: Key('home-drama-genre-${drama.id}'),
+14 -46
View File
@@ -8,28 +8,21 @@ import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/cover_play_count.dart';
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
import 'home_drama_classification.dart';
final RegExp _tagSplitter = RegExp(r'[,/、·]');
enum HomeDramaBadge { hot, newRelease, anime }
class HomeFeedCard extends StatelessWidget {
const HomeFeedCard({
super.key,
required this.drama,
required this.onTap,
this.now,
});
final Drama drama;
final VoidCallback onTap;
final DateTime? now;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Material(
key: Key('home-feed-card-${drama.id}'),
color: AppColors.transparent,
@@ -40,7 +33,7 @@ class HomeFeedCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
_cover(l10n),
_cover(context),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
@@ -51,7 +44,7 @@ class HomeFeedCard extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
drama.title,
drama.localizedTitle(Localizations.localeOf(context).languageCode),
key: Key('home-feed-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -64,7 +57,7 @@ class HomeFeedCard extends StatelessWidget {
),
),
const SizedBox(height: AppDimens.cardTitleTagGap),
_tags(),
_tags(context),
],
),
),
@@ -75,8 +68,8 @@ class HomeFeedCard extends StatelessWidget {
);
}
Widget _cover(AppLocalizations l10n) {
final badge = _badge();
Widget _cover(BuildContext context) {
final label = drama.localizedTag(Localizations.localeOf(context).languageCode);
return ClipRRect(
key: Key('home-feed-cover-clip-${drama.id}'),
borderRadius: BorderRadius.circular(AppDimens.cardCoverRadius),
@@ -92,14 +85,14 @@ class HomeFeedCard extends StatelessWidget {
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
if (badge != null)
if (label.isNotEmpty)
Positioned(
top: 0,
right: 0,
child: DramaCoverBadgeRibbon(
label: _badgeLabel(l10n, badge),
color: _badgeColor(badge),
keyPrefix: '${drama.id}-${badge.name}',
label: label,
color: drama.tagRibbonColor(AppColors.badgeHot),
keyPrefix: '${drama.id}-tag',
),
),
const Positioned(
@@ -122,35 +115,8 @@ class HomeFeedCard extends StatelessWidget {
);
}
HomeDramaBadge? _badge() {
if (drama.dramaType.toUpperCase() == 'ANIME') {
return HomeDramaBadge.anime;
}
if (isNewDrama(drama, now: now)) return HomeDramaBadge.newRelease;
if (isHotDrama(drama)) {
return HomeDramaBadge.hot;
}
return null;
}
String _badgeLabel(AppLocalizations l10n, HomeDramaBadge badge) {
return switch (badge) {
HomeDramaBadge.hot => l10n.homeBadgeHot,
HomeDramaBadge.newRelease => l10n.homeBadgeNew,
HomeDramaBadge.anime => l10n.homeBadgeAnime,
};
}
Color _badgeColor(HomeDramaBadge badge) {
return switch (badge) {
HomeDramaBadge.hot => AppColors.badgeHot,
HomeDramaBadge.newRelease => AppColors.badgeNew,
HomeDramaBadge.anime => AppColors.badgeAnime,
};
}
Widget _tags() {
final tags = _cardTags();
Widget _tags(BuildContext context) {
final tags = _cardTags(context);
if (tags.isEmpty) return const SizedBox.shrink();
return Text(
tags.join(' | '),
@@ -166,7 +132,9 @@ class HomeFeedCard extends StatelessWidget {
);
}
List<String> _cardTags() {
List<String> _cardTags(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(_tagSplitter))
+89 -116
View File
@@ -14,20 +14,16 @@ import '../../../core/data/services/home_feed_controller.dart';
import '../../../core/data/services/wallet_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_theme.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/drama_grid_skeleton.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../l10n/app_localizations.dart';
import '../../ranking/ranking_page.dart';
import 'home_drama_classification.dart';
import 'home_category_dramas.dart';
import 'home_feed_card.dart';
import 'home_grid_header.dart';
const double _loadMoreThreshold = 240;
const List<String> _costumeAliases = ['古装', 'costume', 'period'];
const List<String> _communityAliases = ['社群', 'community', 'komunitas'];
class HomeFeedGrid extends StatefulWidget {
const HomeFeedGrid({
@@ -46,21 +42,15 @@ class HomeFeedGrid extends StatefulWidget {
}
class _HomeFeedGridState extends State<HomeFeedGrid> {
HomePrimaryTab _selectedPrimary = HomePrimaryTab.featured;
int _sectionIndex = 0;
final PageController _pageController = PageController();
final Map<HomePrimaryTab, ScrollController> _scrollControllers = {
for (final tab in HomePrimaryTab.values) tab: ScrollController(),
};
final Map<HomePrimaryTab, String?> _selectedTags = {
for (final tab in HomePrimaryTab.values) tab: null,
};
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _pageController.hasClients) {
_pageController.jumpToPage(_selectedPrimary.index);
_pageController.jumpToPage(_sectionIndex);
}
});
}
@@ -68,9 +58,6 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
@override
void dispose() {
_pageController.dispose();
for (final controller in _scrollControllers.values) {
controller.dispose();
}
super.dispose();
}
@@ -81,17 +68,16 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
final catalog = context.watch<CatalogController>();
final auth = context.watch<AuthController>();
final wallet = context.watch<WalletController>();
final shortcuts = _categoryShortcuts(categories, l10n);
final shortcuts = _categoryShortcuts(
categories,
Localizations.localeOf(context).languageCode,
);
final walletBadge = auth.isSignedIn && wallet.snapshot != null
? wallet.balance
: null;
final ranking = _selectedPrimary == HomePrimaryTab.ranking;
return DecoratedBox(
key: const Key('home-grid'),
decoration: BoxDecoration(
color: ranking ? null : AppColors.appBackground,
gradient: ranking ? AppTheme.pageGradient : null,
),
decoration: const BoxDecoration(color: AppColors.appBackground),
child: SafeArea(
bottom: false,
child: Column(
@@ -100,8 +86,8 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
HomeGridHeader(
callbacks: widget.callbacks,
categories: shortcuts,
selectedPrimary: _selectedPrimary,
onPrimarySelected: _selectPrimary,
selectedIndex: _sectionIndex,
onSectionSelected: _selectSection,
walletBadge: walletBadge,
),
Expanded(
@@ -110,22 +96,29 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
builder: (context, _) => PageView.builder(
key: const Key('home-primary-page-view'),
controller: _pageController,
itemCount: HomePrimaryTab.values.length,
onPageChanged: (index) => setState(
() => _selectedPrimary = HomePrimaryTab.values[index],
),
itemBuilder: (context, index) => _KeepAlivePage(
key: PageStorageKey(
'home-primary-page-${HomePrimaryTab.values[index].name}',
),
child: _tabGrid(
context,
l10n,
tab: HomePrimaryTab.values[index],
catalog: catalog,
shortcuts: shortcuts,
),
),
itemCount: shortcuts.isEmpty ? 1 : shortcuts.length,
onPageChanged: (index) =>
setState(() => _sectionIndex = index),
itemBuilder: (context, index) {
if (shortcuts.isEmpty) {
return _categoryPlaceholder(
l10n,
context.watch<CategoryController>(),
);
}
final category = shortcuts[index];
return _KeepAlivePage(
key: PageStorageKey(
'home-primary-page-${category.categoryId}',
),
child: _tabGrid(
context,
l10n,
category: category,
catalog: catalog,
),
);
},
),
),
),
@@ -135,28 +128,54 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
);
}
void _selectPrimary(HomePrimaryTab tab) {
if (tab == _selectedPrimary) return;
void _selectSection(int index) {
if (index == _sectionIndex) return;
if (!_pageController.hasClients) {
setState(() => _selectedPrimary = tab);
setState(() => _sectionIndex = index);
return;
}
unawaited(
_pageController.animateToPage(
tab.index,
index,
duration: AppDimens.homePrimaryTabAnimationDuration,
curve: Curves.easeOut,
),
);
}
Widget _categoryPlaceholder(
AppLocalizations l10n,
CategoryController controller,
) {
if (controller.loading) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
columns: 3,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
return EmptyState(
key: const Key('home-grid-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
);
}
Widget _tabGrid(
BuildContext context,
AppLocalizations l10n, {
required HomePrimaryTab tab,
required HomeGridCategoryShortcut category,
required CatalogController catalog,
required List<HomeGridCategoryShortcut> shortcuts,
}) {
final controller = context.read<CategoryController>();
if (controller.dramaPageLoader != null && category.categoryId.isNotEmpty) {
return HomeCategoryDramas(
lockedCategoryId: category.categoryId,
onOpenDrama: widget.onOpenDrama,
);
}
if (catalog.error != null && widget.feedController.dramas.isEmpty) {
return _catalogErrorState(l10n, catalog);
}
@@ -170,11 +189,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
if (tab == HomePrimaryTab.ranking) {
return const RankingPage(embedded: true);
}
final tag = _selectedTags[tab];
final dramas = _dramasFor(tab, tag, shortcuts);
final dramas = _dramasFor(category);
if (widget.feedController.loadingFirstPage && dramas.isEmpty) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
@@ -201,7 +216,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
onRefresh: _refresh,
child: CustomScrollView(
key: const Key('home-grid-scroll'),
controller: _scrollControllers[tab],
controller: null,
physics: AppPullToRefresh.physics,
slivers: [
if (dramas.isEmpty)
@@ -237,6 +252,8 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
child: PagedListFooter(
loading: widget.feedController.loadingMore,
hasMore: widget.feedController.hasMore,
hasItems: true,
errorMessage: widget.feedController.lastError == null
? null
: l10n.catalogError,
@@ -289,75 +306,31 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
List<HomeGridCategoryShortcut> _categoryShortcuts(
List<ContentCategory> categories,
AppLocalizations l10n,
String languageCode,
) {
final costume = _findCategory(categories, _costumeAliases);
final community = _findCategory(categories, _communityAliases);
return [
HomeGridCategoryShortcut(
label: l10n.homeSectionCostume,
categoryName: costume?.name ?? '',
tab: HomePrimaryTab.costume,
),
HomeGridCategoryShortcut(
label: l10n.homeSectionCommunity,
categoryName: community?.name ?? '',
tab: HomePrimaryTab.community,
),
for (final category in categories)
HomeGridCategoryShortcut(
label: category.localizedName(languageCode),
categoryName: category.name,
categoryId: category.id,
tab: HomePrimaryTab.categories,
),
];
}
ContentCategory? _findCategory(
List<ContentCategory> categories,
List<String> aliases,
) {
for (final category in categories) {
final name = category.name.toLowerCase();
if (aliases.any(name.contains)) return category;
}
return null;
}
List<Drama> _dramasFor(
HomePrimaryTab tab,
String? tag,
List<HomeGridCategoryShortcut> shortcuts,
) {
Iterable<Drama> source = widget.feedController.dramas;
if (tab == HomePrimaryTab.costume || tab == HomePrimaryTab.community) {
final categoryName = shortcuts
.firstWhere((shortcut) => shortcut.tab == tab)
.categoryName
.toLowerCase();
if (categoryName.isEmpty) return const [];
source = source.where(
(drama) =>
drama.category.toLowerCase().contains(categoryName) ||
drama.genre.toLowerCase().contains(categoryName),
);
}
if (tag != null) {
source = source.where((drama) => matchesHomeTag(drama, tag));
}
final dramas = source.toList(growable: false);
switch (tab) {
case HomePrimaryTab.newReleases:
return [...dramas]..sort((a, b) {
final left = publishedAtForDrama(a);
final right = publishedAtForDrama(b);
if (left == null && right == null) return b.id.compareTo(a.id);
if (left == null) return 1;
if (right == null) return -1;
return right.compareTo(left);
});
case HomePrimaryTab.ranking:
return [...dramas]..sort((a, b) => b.viewCount.compareTo(a.viewCount));
case HomePrimaryTab.featured:
case HomePrimaryTab.categories:
case HomePrimaryTab.costume:
case HomePrimaryTab.community:
return dramas;
}
List<Drama> _dramasFor(HomeGridCategoryShortcut category) {
final dramas = widget.feedController.dramas;
final categoryName = category.categoryName.toLowerCase();
if (categoryName.isEmpty) return dramas;
final matched = dramas
.where(
(drama) =>
drama.category.toLowerCase().contains(categoryName) ||
drama.genre.toLowerCase().contains(categoryName),
)
.toList(growable: false);
return matched.isEmpty ? dramas : matched;
}
Widget _emptyState(AppLocalizations l10n) {
+84 -47
View File
@@ -20,11 +20,13 @@ class HomeGridCategoryShortcut {
const HomeGridCategoryShortcut({
required this.label,
required this.categoryName,
required this.categoryId,
required this.tab,
});
final String label;
final String categoryName;
final String categoryId;
final HomePrimaryTab tab;
}
@@ -47,15 +49,15 @@ class HomeGridHeader extends StatelessWidget {
super.key,
required this.callbacks,
required this.categories,
required this.selectedPrimary,
required this.onPrimarySelected,
required this.selectedIndex,
required this.onSectionSelected,
this.walletBadge,
});
final HomeGridCallbacks callbacks;
final List<HomeGridCategoryShortcut> categories;
final HomePrimaryTab selectedPrimary;
final ValueChanged<HomePrimaryTab> onPrimarySelected;
final int selectedIndex;
final ValueChanged<int> onSectionSelected;
final int? walletBadge;
@override
@@ -67,7 +69,7 @@ class HomeGridHeader extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.start,
children: [
_searchRow(l10n),
_primaryRow(l10n),
_primaryRow(),
const SizedBox(height: AppDimens.homeSecondaryGridGap),
],
);
@@ -225,7 +227,73 @@ class HomeGridHeader extends StatelessWidget {
);
}
Widget _primaryRow(AppLocalizations l10n) {
Widget _primaryRow() {
return _CategoryBar(
categories: categories,
selectedIndex: selectedIndex,
onSectionSelected: onSectionSelected,
);
}
}
class _CategoryBar extends StatefulWidget {
const _CategoryBar({
required this.categories,
required this.selectedIndex,
required this.onSectionSelected,
});
final List<HomeGridCategoryShortcut> categories;
final int selectedIndex;
final ValueChanged<int> onSectionSelected;
@override
State<_CategoryBar> createState() => _CategoryBarState();
}
class _CategoryBarState extends State<_CategoryBar> {
final List<GlobalKey> _itemKeys = [];
@override
void initState() {
super.initState();
_syncKeys();
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
}
@override
void didUpdateWidget(_CategoryBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.categories.length != widget.categories.length) {
_syncKeys();
}
if (oldWidget.selectedIndex != widget.selectedIndex ||
oldWidget.categories.length != widget.categories.length) {
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
}
}
void _syncKeys() {
_itemKeys
..clear()
..addAll(List.generate(widget.categories.length, (_) => GlobalKey()));
}
void _revealSelected() {
final index = widget.selectedIndex;
if (!mounted || index < 0 || index >= _itemKeys.length) return;
final target = _itemKeys[index].currentContext;
if (target == null) return;
Scrollable.ensureVisible(
target,
alignment: 0.5,
duration: AppDimens.homePrimaryTabAnimationDuration,
curve: Curves.easeOut,
);
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
key: const Key('home-primary-sections'),
scrollDirection: Axis.horizontal,
@@ -234,60 +302,29 @@ class HomeGridHeader extends StatelessWidget {
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
_primaryItem(
key: const Key('home-section-featured'),
label: l10n.homeSectionFeatured,
tab: HomePrimaryTab.featured,
),
_primaryItem(
key: const Key('home-section-new'),
label: l10n.homeSectionNew,
tab: HomePrimaryTab.newReleases,
),
_primaryItem(
key: const Key('home-section-categories'),
label: l10n.homeSectionCategories,
tab: HomePrimaryTab.categories,
),
_primaryItem(
key: const Key('home-section-ranking'),
label: l10n.homeSectionRanking,
tab: HomePrimaryTab.ranking,
),
for (final category in categories)
_primaryItem(
key: Key(
category.categoryName.isEmpty
? 'home-section-${category.tab.name}'
: 'home-section-category-${category.categoryName}',
),
label: category.label,
tab: category.tab,
),
for (var index = 0; index < widget.categories.length; index++)
_item(index),
],
),
);
}
Widget _primaryItem({
required Key key,
required String label,
required HomePrimaryTab tab,
}) {
final selected = selectedPrimary == tab;
Widget _item(int index) {
final category = widget.categories[index];
final selected = widget.selectedIndex == index;
return InkWell(
key: key,
onTap: () => onPrimarySelected(tab),
key: _itemKeys[index],
onTap: () => widget.onSectionSelected(index),
child: Padding(
key: Key('home-section-category-${category.categoryName}'),
padding: const EdgeInsets.only(right: AppDimens.homePrimaryCategoryGap),
child: SizedBox(
height: AppDimens.homePrimaryRowHeight,
child: Align(
alignment: Alignment.bottomLeft,
child: AnimatedDefaultTextStyle(
key: Key('home-primary-label-${tab.name}'),
key: Key('home-primary-label-${category.categoryId}'),
duration: AppDimens.homePrimaryTabAnimationDuration,
curve: Curves.easeOut,
style: TextStyle(
@@ -300,7 +337,7 @@ class HomeGridHeader extends StatelessWidget {
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
letterSpacing: 0,
),
child: Text(label, textAlign: TextAlign.left),
child: Text(category.label, textAlign: TextAlign.left),
),
),
),
@@ -82,7 +82,11 @@ class MineContinueWatching extends StatelessWidget {
const SizedBox(width: AppDimens.spaceMd),
itemBuilder: (_, index) {
final record = visible[index];
return _card(l10n, record);
return _card(
l10n,
record,
Localizations.localeOf(context).languageCode,
);
},
),
),
@@ -90,8 +94,8 @@ class MineContinueWatching extends StatelessWidget {
);
}
Widget _card(AppLocalizations l10n, WatchProgress record) {
final title = record.dramaTitle?.trim() ?? '';
Widget _card(AppLocalizations l10n, WatchProgress record, String languageCode) {
final title = record.localizedTitle(languageCode).trim();
final episode = record.episodeNumber;
final hasProgress = record.duration > Duration.zero;
return SizedBox(
@@ -192,6 +192,8 @@ class _NewReleasesPageState extends State<NewReleasesPage> {
),
PagedLoadFooter(
loading: pager.loading,
hasMore: pager.hasMore,
hasItems: visible.isNotEmpty,
loadMoreKey: const Key(
'new-releases-load-more',
),
+11
View File
@@ -171,6 +171,17 @@ class _NoticesPageState extends State<NoticesPage> {
label: Text(l10n.retry),
);
}
if (_controller.notices.isNotEmpty && !_controller.hasMore) {
return Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
);
}
return const SizedBox.shrink();
}
@@ -0,0 +1,119 @@
// Author: fruit.com.cn
// 评论楼中楼:展开回复、继续加载,没有下一页时给出结束提示。
import 'package:flutter/material.dart';
import '../../../core/data/models/comment.dart';
import '../../../core/data/services/comment_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import 'comment_tile.dart';
const double _replyIndent = 52;
/// 一条评论及其回复。
class CommentThread extends StatelessWidget {
const CommentThread({
super.key,
required this.comment,
required this.controller,
required this.handlers,
});
final DramaComment comment;
final CommentController controller;
final CommentInteractionHandlers handlers;
@override
Widget build(BuildContext context) {
final replies = controller.repliesFor(comment.id);
final expanded = controller.repliesExpanded(comment.id);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CommentTile(comment: comment, handlers: handlers),
if (comment.replyCount > 0 || replies.isNotEmpty) _toggle(context, expanded),
if (expanded) _replies(context, replies),
],
);
}
Widget _toggle(BuildContext context, bool expanded) {
final l10n = AppLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.only(left: _replyIndent, bottom: 4),
child: TextButton(
key: Key('comment-replies-${comment.id}'),
onPressed: () => _toggleReplies(context),
style: TextButton.styleFrom(
foregroundColor: AppColors.muted,
padding: EdgeInsets.zero,
minimumSize: const Size(0, 24),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(width: 16, height: 1, color: AppColors.border),
const SizedBox(width: 8),
Text(
expanded ? l10n.hideReplies : l10n.viewReplies(comment.replyCount),
style: const TextStyle(
color: AppColors.muted,
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
const SizedBox(width: 4),
Icon(
expanded
? Icons.keyboard_arrow_up_rounded
: Icons.keyboard_arrow_down_rounded,
size: 14,
color: AppColors.muted,
),
],
),
),
);
}
Widget _replies(BuildContext context, List<DramaComment> replies) {
final l10n = AppLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.only(left: _replyIndent),
child: Column(
children: [
if (controller.repliesLoading(comment.id))
const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: CircularProgressIndicator(),
),
for (final reply in replies)
CommentTile(comment: reply, handlers: handlers, isReply: true),
if (controller.repliesHasMore(comment.id))
TextButton(
onPressed: () => controller.loadMoreReplies(comment.id),
child: Text(l10n.loadMore),
)
else if (replies.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
l10n.noMoreItems,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
),
],
),
);
}
Future<void> _toggleReplies(BuildContext context) async {
if (controller.repliesExpanded(comment.id)) {
controller.hideReplies(comment.id);
return;
}
await controller.loadReplies(comment.id);
}
}
@@ -19,6 +19,7 @@ import '../../../core/widgets/auth_gate.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../l10n/app_localizations.dart';
import 'comment_composer_sheet.dart';
import 'comment_thread.dart';
import 'comment_tile.dart';
const double _composerRadius = 22;
@@ -26,7 +27,6 @@ const double _composerHeight = 44;
const double _sendButtonSize = 38;
const double _sheetRadius = 20;
const double _headerHeight = 44;
const double _replyIndent = 52;
const double _composerTopGap = 8;
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与登录发布。
@@ -315,7 +315,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
itemCount: _controller.comments.length + 1,
itemBuilder: (context, index) {
if (index == _controller.comments.length) return _footer(l10n);
return _CommentThread(
return CommentThread(
comment: _controller.comments[index],
controller: _controller,
handlers: CommentInteractionHandlers(onReply: _beginReply),
@@ -338,6 +338,17 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
child: Text(l10n.loadMore),
);
}
if (_controller.comments.isNotEmpty) {
return Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
);
}
return const SizedBox(height: 8);
}
@@ -435,100 +446,3 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
);
}
}
class _CommentThread extends StatelessWidget {
const _CommentThread({
required this.comment,
required this.controller,
required this.handlers,
});
final DramaComment comment;
final CommentController controller;
final CommentInteractionHandlers handlers;
@override
Widget build(BuildContext context) {
final replies = controller.repliesFor(comment.id);
final expanded = controller.repliesExpanded(comment.id);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CommentTile(comment: comment, handlers: handlers),
if (comment.replyCount > 0 || replies.isNotEmpty)
Padding(
padding: const EdgeInsets.only(left: _replyIndent, bottom: 4),
child: TextButton(
key: Key('comment-replies-${comment.id}'),
onPressed: () => _toggleReplies(context),
style: TextButton.styleFrom(
foregroundColor: AppColors.muted,
padding: EdgeInsets.zero,
minimumSize: const Size(0, 24),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(width: 16, height: 1, color: AppColors.border),
const SizedBox(width: 8),
Text(
expanded
? AppLocalizations.of(context)!.hideReplies
: AppLocalizations.of(
context,
)!.viewReplies(comment.replyCount),
style: const TextStyle(
color: AppColors.muted,
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
const SizedBox(width: 4),
Icon(
expanded
? Icons.keyboard_arrow_up_rounded
: Icons.keyboard_arrow_down_rounded,
size: 14,
color: AppColors.muted,
),
],
),
),
),
if (expanded)
Padding(
padding: const EdgeInsets.only(left: _replyIndent),
child: Column(
children: [
if (controller.repliesLoading(comment.id))
const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: CircularProgressIndicator(),
),
for (final reply in replies)
CommentTile(
comment: reply,
handlers: handlers,
isReply: true,
),
if (controller.repliesHasMore(comment.id))
TextButton(
onPressed: () => controller.loadMoreReplies(comment.id),
child: Text(AppLocalizations.of(context)!.loadMore),
),
],
),
),
],
);
}
Future<void> _toggleReplies(BuildContext context) async {
if (controller.repliesExpanded(comment.id)) {
controller.hideReplies(comment.id);
return;
}
await controller.loadReplies(comment.id);
}
}
@@ -49,7 +49,7 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
final l10n = AppLocalizations.of(context)!;
final dramaTitle = localizedDramaTitle(l10n, widget.drama);
final synopsis = localizedDramaSynopsis(l10n, widget.drama).trim();
final genres = _genreValues();
final genres = _genreValues(Localizations.localeOf(context).languageCode);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -285,7 +285,9 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
);
}
List<String> _genreValues() {
List<String> _genreValues(String languageCode) {
final localized = widget.drama.localizedTypeLabels(languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
final result = <String>[];
for (final value in [widget.drama.genre, widget.drama.category]) {
for (final part in value.split(_tagSplitter)) {
+2
View File
@@ -153,6 +153,8 @@ class _RankingPageState extends State<RankingPage> {
],
PagedLoadFooter(
loading: _pager!.loading,
hasMore: _pager!.hasMore,
hasItems: _pager!.visibleItems.isNotEmpty,
loadMoreKey: const Key('ranking-load-more'),
),
],
+80
View File
@@ -6,8 +6,11 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/remote/catalog_api.dart';
import '../../core/data/models/playlist_detail.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/data/services/home_feed_controller.dart';
import '../../core/data/services/playlist_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
@@ -23,6 +26,7 @@ class RecommendPage extends StatefulWidget {
const RecommendPage({
super.key,
required this.feedController,
this.catalogApi,
required this.active,
required this.onSearch,
this.videoOnly = false,
@@ -30,6 +34,7 @@ class RecommendPage extends StatefulWidget {
});
final HomeFeedController feedController;
final CatalogApi? catalogApi;
final bool active;
final VoidCallback onSearch;
@@ -46,6 +51,32 @@ class _RecommendPageState extends State<RecommendPage> {
final PageController _pageController = PageController();
int _scrubCancelRequest = 0;
@override
void initState() {
super.initState();
if (widget.active) _scheduleRecommendData();
}
@override
void didUpdateWidget(RecommendPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.active && !oldWidget.active) _scheduleRecommendData();
}
void _scheduleRecommendData() {
final feed = widget.feedController;
if (!feed.loaded && !feed.loadingFirstPage) {
unawaited(feed.refreshCurrent());
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !widget.active) return;
final playlists = _readPlaylists();
if (playlists != null && !playlists.loaded && !playlists.loading) {
unawaited(playlists.load());
}
});
}
@override
void dispose() {
_pageController.dispose();
@@ -82,6 +113,7 @@ class _RecommendPageState extends State<RecommendPage> {
child: _withTopNavSpace(
AllDramasFilterGrid(
feedController: widget.feedController,
catalogApi: widget.catalogApi,
onOpenDrama: _openDrama,
),
),
@@ -168,6 +200,22 @@ class _RecommendPageState extends State<RecommendPage> {
);
}
PlaylistController? _watchPlaylists(BuildContext context) {
try {
return context.watch<PlaylistController>();
} on ProviderNotFoundException {
return null;
}
}
PlaylistController? _readPlaylists() {
try {
return context.read<PlaylistController>();
} on ProviderNotFoundException {
return null;
}
}
Widget _recommendPlaylists(CategoryController categories) {
return DecoratedBox(
key: const Key('recommend-playlist-surface'),
@@ -205,6 +253,8 @@ class _RecommendPageState extends State<RecommendPage> {
categories: categories,
onOpenDrama: _openDrama,
onMore: _handleMore,
playlists: _watchPlaylists(context),
onOpenPlaylist: _openPlaylist,
),
),
],
@@ -252,6 +302,36 @@ class _RecommendPageState extends State<RecommendPage> {
);
}
Future<void> _openPlaylist(PlaylistDetail playlist) async {
final controller = _readPlaylists();
const pageSize = CatalogApi.playlistDramaPageSize;
final fresh = controller == null
? playlist
: await controller.detail(playlist.id, pageSize: pageSize);
if (!mounted) return;
final shown = fresh.dramas.isEmpty && playlist.dramas.isNotEmpty
? playlist
: fresh;
await Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (_) => PlaylistDetailPage(
title: shown.name,
subtitle: shown.description,
source: shown,
dramas: shown.dramas,
dramaCount: shown.dramaCount,
loadPage: controller == null
? null
: (pageIndex) => controller.detail(
playlist.id,
pageIndex: pageIndex,
pageSize: pageSize,
),
),
),
);
}
void _handleMore(RecommendSectionKind section) {
final l10n = AppLocalizations.of(context)!;
final copy = _sectionCopy(l10n, section);
@@ -1,10 +1,14 @@
// Author: fruit.com.cn
// 全部短剧:分类、类型、标签多选,列表下拉刷新、上拉加载。
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../core/data/models/content_category.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/remote/catalog_api.dart';
import '../../../core/data/services/all_dramas_controller.dart';
import '../../../core/data/services/home_feed_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
@@ -12,21 +16,24 @@ import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
import '../../home/widgets/home_feed_card.dart';
const double _loadMoreThreshold = 240;
const List<String> _modernTerms = ['现代', 'modern', 'moderno'];
const List<String> _reversalTerms = ['逆袭', 'comeback', 'balas'];
const int _gridColumns = 3;
/// 推荐页「全部短剧」筛选和三列列表。
class AllDramasFilterGrid extends StatefulWidget {
const AllDramasFilterGrid({
super.key,
required this.feedController,
required this.onOpenDrama,
this.feedController,
this.catalogApi,
this.controller,
});
final HomeFeedController feedController;
final HomeFeedController? feedController;
final CatalogApi? catalogApi;
final AllDramasController? controller;
final ValueChanged<Drama> onOpenDrama;
@override
@@ -34,102 +41,143 @@ class AllDramasFilterGrid extends StatefulWidget {
}
class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
String _region = 'all';
String _audio = 'all';
String? _genre;
bool _newest = false;
late final AllDramasController _library;
@override
void initState() {
super.initState();
_library = widget.controller ??
AllDramasController(
api: widget.catalogApi == null
? null
: CatalogAllDramasRemote(widget.catalogApi!),
);
if (_library.usesRemote) {
unawaited(_reload());
}
}
Future<void> _reload() async {
await _library.refresh();
if (mounted) setState(() {});
}
Future<void> _loadMore() async {
if (_library.usesRemote) {
await _library.loadMore();
if (mounted) setState(() {});
return;
}
await widget.feedController?.loadMore();
}
List<Drama> get _dramas =>
_library.usesRemote ? _library.dramas : widget.feedController?.dramas ?? _library.dramas;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final dramas = _filtered();
return LayoutBuilder(
builder: (context, constraints) {
final itemWidth =
(constraints.maxWidth -
AppDimens.allDramasHorizontal * 2 -
AppDimens.allDramasGridGap * 2) /
3;
final itemExtent =
itemWidth / AppDimens.cardCoverAspectRatio +
AppDimens.homeCardBodyExtent;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_filters(l10n),
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
key: const Key('all-dramas-refresh'),
onRefresh: () async {
await widget.feedController.refreshCurrent();
},
child: CustomScrollView(
key: const Key('all-dramas-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
if (dramas.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: EmptyState(
key: const Key('all-dramas-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
),
)
else
SliverPadding(
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.allDramasHorizontal,
),
sliver: SliverGrid(
key: const Key('all-dramas-grid'),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: AppDimens.allDramasGridGap,
mainAxisSpacing:
AppDimens.allDramasGridRowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => widget.onOpenDrama(dramas[index]),
),
childCount: dramas.length,
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(
bottom: AppDimens.spaceXl,
),
child: PagedListFooter(
loading: widget.feedController.loadingMore,
errorMessage:
widget.feedController.lastError == null
? null
: l10n.catalogError,
onRetry: widget.feedController.loadMore,
),
),
),
],
),
),
),
),
Expanded(child: _dramaList(l10n, _itemExtent(constraints.maxWidth))),
],
);
},
);
}
double _itemExtent(double width) {
final itemWidth =
(width - AppDimens.allDramasHorizontal * 2 - AppDimens.allDramasGridGap * 2) /
_gridColumns;
return itemWidth / AppDimens.cardCoverAspectRatio + AppDimens.homeCardBodyExtent;
}
Widget _dramaList(AppLocalizations l10n, double itemExtent) {
final dramas = _dramas;
return NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
key: const Key('all-dramas-refresh'),
onRefresh: _refresh,
child: CustomScrollView(
key: const Key('all-dramas-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
if (dramas.isEmpty) _empty(l10n) else _grid(dramas, itemExtent),
_footer(l10n, dramas.isNotEmpty),
],
),
),
);
}
Future<void> _refresh() async {
if (_library.usesRemote) {
await _reload();
return;
}
await widget.feedController?.refreshCurrent();
}
Widget _empty(AppLocalizations l10n) {
return SliverFillRemaining(
hasScrollBody: false,
child: EmptyState(
key: const Key('all-dramas-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
),
);
}
Widget _grid(List<Drama> dramas, double itemExtent) {
return SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: AppDimens.allDramasHorizontal),
sliver: SliverGrid(
key: const Key('all-dramas-grid'),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: _gridColumns,
crossAxisSpacing: AppDimens.allDramasGridGap,
mainAxisSpacing: AppDimens.allDramasGridRowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => widget.onOpenDrama(dramas[index]),
),
childCount: dramas.length,
),
),
);
}
Widget _footer(AppLocalizations l10n, bool hasItems) {
return SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
child: PagedListFooter(
loading: _library.usesRemote
? _library.loadingMore
: widget.feedController?.loadingMore ?? false,
hasMore: _library.usesRemote
? _library.hasMore
: widget.feedController?.hasMore ?? false,
hasItems: hasItems,
errorMessage: _library.error == null ? null : l10n.catalogError,
onRetry: _loadMore,
),
),
);
}
Widget _filters(AppLocalizations l10n) {
final genres = _availableGenres(l10n);
final languageCode = Localizations.localeOf(context).languageCode;
return Padding(
padding: const EdgeInsets.fromLTRB(
AppDimens.allDramasHorizontal,
@@ -140,60 +188,75 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
child: Column(
key: const Key('all-dramas-filters'),
children: [
_selectableRow(
0,
[
(id: 'all', label: l10n.all),
(id: 'local', label: l10n.localFilter),
(id: 'asia', label: l10n.asiaFilter),
(id: 'western', label: l10n.westernFilter),
],
selected: _region,
onSelected: (value) => setState(() => _region = value),
_optionRow(
_FilterRow(
row: 0,
group: 'classification',
options: _library.classifications,
selected: _library.selectedClassifications,
onToggle: _library.toggleClassification,
),
languageCode,
l10n,
),
_selectableRow(
1,
[
(id: 'all', label: l10n.all),
(id: 'subtitles', label: l10n.subtitlesOnlyFilter),
(id: 'dubbed', label: l10n.dubbedFilter),
],
selected: _audio,
onSelected: (value) => setState(() => _audio = value),
_optionRow(
_FilterRow(
row: 1,
group: 'category',
options: _library.categories,
selected: _library.selectedCategories,
onToggle: _library.toggleCategory,
),
languageCode,
l10n,
),
_optionRow(
_FilterRow(
row: 2,
group: 'tag',
options: _library.tags,
selected: _library.selectedTags,
onToggle: _library.toggleTag,
),
languageCode,
l10n,
),
_genreRow(2, genres, l10n),
_sortRow(l10n),
],
),
);
}
Widget _selectableRow(
int row,
List<({String id, String label})> options, {
required String selected,
required ValueChanged<String> onSelected,
}) {
Widget _optionRow(_FilterRow spec, String languageCode, AppLocalizations l10n) {
return _filterRow(
row: row,
row: spec.row,
child: _horizontalChipScroll(
scrollKey: Key('all-filter-scroll-$row'),
scrollKey: Key('all-filter-scroll-${spec.row}'),
chips: [
for (var index = 0; index < options.length; index++) ...[
_chip(
key: Key('all-filter-${spec.group}-all'),
label: l10n.all,
selected: spec.selected.isEmpty,
onTap: () => _select(spec.onToggle, ''),
),
for (final option in spec.options) ...[
const SizedBox(width: AppDimens.filterItemGap),
_chip(
key: Key('all-filter-${options[index].id}'),
label: options[index].label,
selected: selected == options[index].id,
onTap: () => onSelected(options[index].id),
key: Key('all-filter-${spec.group}-${option.id}'),
label: option.localizedName(languageCode),
selected: spec.selected.contains(option.id),
onTap: () => _select(spec.onToggle, option.id),
),
if (index < options.length - 1)
const SizedBox(width: AppDimens.filterItemGap),
],
],
),
);
}
void _select(void Function(String id) onToggle, String id) {
setState(() => onToggle(id));
if (_library.usesRemote) unawaited(_reload());
}
Widget _horizontalChipScroll({
required Key scrollKey,
required List<Widget> chips,
@@ -205,43 +268,17 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
physics: const BouncingScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: chips,
),
child: Row(children: chips),
),
),
);
}
Widget _filterRow({
required int row,
required Widget child,
double height = AppDimens.filterChipHeight,
}) {
Widget _filterRow({required int row, required Widget child}) {
return Padding(
key: Key('all-filter-row-$row'),
padding: EdgeInsets.only(bottom: row < 3 ? AppDimens.filterRowGap : 0),
child: SizedBox(height: height, child: child),
);
}
Widget _genreRow(
int row,
List<({String id, String label})> options,
AppLocalizations l10n,
) {
return _selectableRow(
row,
[
(id: 'all', label: l10n.all),
for (final genre in options) (id: genre.id, label: genre.label),
],
selected: _genre ?? 'all',
onSelected: (value) =>
setState(() => _genre = value == 'all' ? null : value),
padding: EdgeInsets.only(bottom: row < 2 ? AppDimens.filterRowGap : 0),
child: SizedBox(height: AppDimens.filterChipHeight, child: child),
);
}
@@ -262,9 +299,7 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
),
alignment: Alignment.center,
decoration: BoxDecoration(
color: selected
? AppColors.filterChipSelected
: AppColors.transparent,
color: selected ? AppColors.filterChipSelected : AppColors.transparent,
borderRadius: BorderRadius.circular(AppDimens.filterChipRadius),
),
child: Text(
@@ -282,84 +317,32 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
);
}
Widget _sortRow(AppLocalizations l10n) {
return _filterRow(
row: 3,
child: _horizontalChipScroll(
scrollKey: const Key('all-filter-scroll-3'),
chips: [
_chip(
key: const Key('all-sort-hot'),
label: l10n.hot,
selected: !_newest,
onTap: () => setState(() => _newest = false),
),
const SizedBox(width: AppDimens.filterItemGap),
_chip(
key: const Key('all-sort-new'),
label: l10n.newest,
selected: _newest,
onTap: () => setState(() => _newest = true),
),
],
),
);
}
List<({String id, String label})> _availableGenres(AppLocalizations l10n) {
final definitions = [
(id: 'reversal', label: l10n.reversalFilter, terms: _reversalTerms),
(id: 'uplifting', label: l10n.homeTagUplifting, terms: <String>[]),
(id: 'modern', label: l10n.modernFilter, terms: _modernTerms),
(id: 'sweet', label: l10n.homeTagSweet, terms: <String>[]),
(id: 'angst', label: l10n.homeTagAngst, terms: <String>[]),
];
return definitions
.map((definition) => (id: definition.id, label: definition.label))
.toList(growable: false);
}
List<Drama> _filtered() {
if (_region != 'all' || _audio != 'all') return const [];
final dramas = widget.feedController.dramas
.where((drama) {
return _genre == null || _matchesGenre(drama, _genre!, const []);
})
.toList(growable: false);
if (_newest) {
return [...dramas]..sort((a, b) {
final left = publishedAtForDrama(a);
final right = publishedAtForDrama(b);
if (left == null && right == null) return b.id.compareTo(a.id);
if (left == null) return 1;
if (right == null) return -1;
return right.compareTo(left);
});
}
return [...dramas]..sort((a, b) => b.viewCount.compareTo(a.viewCount));
}
bool _matchesGenre(Drama drama, String id, List<String> terms) {
if (id == 'reversal' ||
id == 'uplifting' ||
id == 'sweet' ||
id == 'angst') {
return matchesHomeTag(drama, id == 'reversal' ? 'uplifting' : id);
}
final text = '${drama.genre} ${drama.category}'.toLowerCase();
return terms.any(text.contains);
}
bool _onScroll(ScrollNotification notification) {
if (notification.depth != 0) return false;
final reachedBottom =
notification.metrics.extentAfter <= _loadMoreThreshold;
if (notification.metrics.pixels <= 0) return false;
final reachedBottom = notification.metrics.extentAfter <= _loadMoreThreshold;
if (reachedBottom &&
(notification is ScrollUpdateNotification ||
notification is ScrollEndNotification ||
notification is OverscrollNotification)) {
unawaited(widget.feedController.loadMore());
unawaited(_loadMore());
}
return false;
}
}
class _FilterRow {
const _FilterRow({
required this.row,
required this.group,
required this.options,
required this.selected,
required this.onToggle,
});
final int row;
final String group;
final List<ContentCategory> options;
final Set<String> selected;
final void Function(String id) onToggle;
}
@@ -3,15 +3,20 @@
import 'package:flutter/material.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/models/playlist_detail.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_theme.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_feed_card.dart';
import '../../player/open_player.dart';
const double _collageHeight = 188;
const int _collageCoverCount = 5;
const double _loadMoreThreshold = 200;
const double _pageHorizontal = 14;
const double _gridGap = 10;
const double _sprocketBand = 22;
@@ -19,17 +24,88 @@ const Color _filmBody = Color(0xFF161311);
const Color _filmHole = Color(0xFFE6D3BE);
/// 剧单「更多」:顶部拼图、与剧单一致的标题描述,以及两列卡片。
class PlaylistDetailPage extends StatelessWidget {
class PlaylistDetailPage extends StatefulWidget {
const PlaylistDetailPage({
super.key,
required this.title,
required this.subtitle,
required this.dramas,
this.dramaCount = 0,
this.source,
this.loadPage,
});
final String title;
final String subtitle;
final List<Drama> dramas;
final PlaylistDetail? source;
final int dramaCount;
final Future<PlaylistDetail> Function(int pageIndex)? loadPage;
@override
State<PlaylistDetailPage> createState() => _PlaylistDetailPageState();
}
class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
late List<Drama> _dramas = widget.dramas;
late int _dramaCount = widget.dramaCount;
int _pageIndex = 1;
bool _loadingMore = false;
bool _failed = false;
bool get _hasMore =>
widget.loadPage != null && _dramas.length < _dramaCount;
Future<void> _refresh() async {
final loadPage = widget.loadPage;
if (loadPage == null) return;
try {
final page = await loadPage(1);
if (!mounted) return;
setState(() {
_dramas = page.dramas;
_dramaCount = page.dramaCount;
_pageIndex = page.pageIndex == 0 ? 1 : page.pageIndex;
_failed = false;
});
} catch (_) {
if (!mounted) return;
setState(() => _failed = true);
}
}
Future<void> _loadMore() async {
final loadPage = widget.loadPage;
if (loadPage == null || _loadingMore || !_hasMore) return;
setState(() => _loadingMore = true);
final next = _pageIndex + 1;
try {
final page = await loadPage(next);
if (!mounted) return;
setState(() {
_dramas = [..._dramas, ...page.dramas];
_dramaCount = page.dramaCount;
_pageIndex = page.pageIndex == 0 ? next : page.pageIndex;
_failed = false;
});
} catch (_) {
if (!mounted) return;
setState(() => _failed = true);
} finally {
if (mounted) setState(() => _loadingMore = false);
}
}
bool _onScroll(ScrollNotification notification) {
if (!_hasMore || notification.depth != 0) return false;
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification) {
return false;
}
_loadMore();
return false;
}
@override
Widget build(BuildContext context) {
@@ -52,7 +128,16 @@ class PlaylistDetailPage extends StatelessWidget {
icon: const Icon(Icons.chevron_left_rounded),
color: AppColors.textPrimary,
),
Expanded(child: _body(itemExtent)),
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
key: const Key('playlist-detail-refresh'),
onRefresh: _refresh,
child: _body(itemExtent),
),
),
),
],
),
),
@@ -63,6 +148,7 @@ class PlaylistDetailPage extends StatelessWidget {
Widget _body(double itemExtent) {
return CustomScrollView(
key: const Key('playlist-detail-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
SliverPadding(
padding: const EdgeInsets.fromLTRB(
@@ -71,7 +157,7 @@ class PlaylistDetailPage extends StatelessWidget {
_pageHorizontal,
12,
),
sliver: SliverToBoxAdapter(child: _PlaylistCollage(dramas: dramas)),
sliver: SliverToBoxAdapter(child: _PlaylistCollage(dramas: _dramas)),
),
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: _pageHorizontal),
@@ -95,10 +181,22 @@ class PlaylistDetailPage extends StatelessWidget {
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => playDramaFromCatalog(context, dramas[index]),
drama: _dramas[index],
onTap: () => playDramaFromCatalog(context, _dramas[index]),
),
childCount: dramas.length,
childCount: _dramas.length,
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 24),
child: PagedListFooter(
loading: _loadingMore,
hasMore: _hasMore,
hasItems: _dramas.isNotEmpty,
errorMessage: _failed ? AppLocalizations.of(context)!.catalogError : null,
onRetry: _loadingMore ? _loadMore : (_hasMore ? _loadMore : _refresh),
),
),
),
@@ -106,12 +204,26 @@ class PlaylistDetailPage extends StatelessWidget {
);
}
String _title(BuildContext context) {
final item = widget.source;
if (item == null) return widget.title;
return item.localizedName(Localizations.localeOf(context).languageCode);
}
String _subtitle(BuildContext context) {
final item = widget.source;
if (item == null) return widget.subtitle;
return item.localizedDescription(
Localizations.localeOf(context).languageCode,
);
}
Widget _heading() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
_title(context),
key: const Key('playlist-detail-title'),
style: const TextStyle(
color: AppColors.textPrimary,
@@ -121,7 +233,7 @@ class PlaylistDetailPage extends StatelessWidget {
),
const SizedBox(height: 2),
Text(
subtitle,
_subtitle(context),
key: const Key('playlist-detail-subtitle'),
style: const TextStyle(
color: AppColors.textSecondary,
@@ -8,8 +8,6 @@ import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/cover_play_count.dart';
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
final RegExp _tagSplitter = RegExp(r'[,/、·]');
@@ -27,7 +25,7 @@ class RecommendSectionCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final tagLabel = drama.localizedTag(Localizations.localeOf(context).languageCode);
return SizedBox(
width: AppDimens.recommendCardWidth,
child: InkWell(
@@ -52,14 +50,14 @@ class RecommendSectionCard extends StatelessWidget {
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
if (isHotDrama(drama))
if (tagLabel.isNotEmpty)
Positioned(
top: 0,
right: 0,
child: DramaCoverBadgeRibbon(
label: l10n.homeBadgeHot,
color: AppColors.badgeHot,
keyPrefix: '$sectionKey-${drama.id}-hot',
label: tagLabel,
color: drama.tagRibbonColor(AppColors.badgeHot),
keyPrefix: '$sectionKey-${drama.id}-tag',
),
),
const Positioned(
@@ -82,7 +80,7 @@ class RecommendSectionCard extends StatelessWidget {
),
const SizedBox(height: AppDimens.cardCoverTitleGap),
Text(
drama.title,
drama.localizedTitle(Localizations.localeOf(context).languageCode),
key: Key('recommend-title-$sectionKey-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -94,25 +92,15 @@ class RecommendSectionCard extends StatelessWidget {
),
),
const SizedBox(height: AppDimens.cardTitleTagGap),
_tags(),
_tags(context),
],
),
),
);
}
List<String> _cardTags() {
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(_tagSplitter))
.map((value) => value.trim())
.where((value) => value.isNotEmpty && seen.add(value))
.take(3)
.toList(growable: false);
}
Widget _tags() {
final tags = _cardTags();
Widget _tags(BuildContext context) {
final tags = _cardTags(context);
if (tags.isEmpty) return const SizedBox.shrink();
return Text(
tags.join(' | '),
@@ -126,4 +114,16 @@ class RecommendSectionCard extends StatelessWidget {
),
);
}
List<String> _cardTags(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(_tagSplitter))
.map((value) => value.trim())
.where((value) => value.isNotEmpty && seen.add(value))
.take(3)
.toList(growable: false);
}
}
@@ -4,17 +4,21 @@ import 'package:flutter/material.dart';
import '../../../core/data/models/content_category.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/models/playlist_detail.dart';
import '../../../core/data/services/category_controller.dart';
import '../../../core/data/services/home_feed_controller.dart';
import '../../../core/data/services/playlist_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
import 'recommend_section_card.dart';
const List<String> _costumeNames = ['古装', 'costume', 'kostum'];
const int _sectionPreviewCount = 10;
const double _loadMoreThreshold = 200;
enum RecommendSectionKind { hits, newReleases, costume }
@@ -25,17 +29,51 @@ class RecommendSectionsView extends StatelessWidget {
required this.categories,
required this.onOpenDrama,
required this.onMore,
this.playlists,
this.onOpenPlaylist,
});
final HomeFeedController feedController;
final CategoryController categories;
final ValueChanged<Drama> onOpenDrama;
final ValueChanged<RecommendSectionKind> onMore;
final PlaylistController? playlists;
final ValueChanged<PlaylistDetail>? onOpenPlaylist;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final source = feedController.dramas;
final remote = playlists;
return AppPullToRefresh(
key: const Key('recommend-sections-refresh'),
onRefresh: () async {
await Future.wait([
feedController.refreshCurrent(),
categories.load(),
if (remote != null) remote.load(),
]);
},
child: NotificationListener<ScrollNotification>(
onNotification: (notification) =>
remote == null ? false : _onPlaylistScroll(notification, remote),
child: ListView(
key: const Key('recommend-sections-scroll'),
physics: AppPullToRefresh.physics,
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
children: remote == null
? _localSections(context, l10n, source)
: _remoteSections(context, l10n, remote),
),
),
);
}
List<Widget> _localSections(
BuildContext context,
AppLocalizations l10n,
List<Drama> source,
) {
final hits = recommendSectionDramas(
kind: RecommendSectionKind.hits,
source: source,
@@ -44,16 +82,7 @@ class RecommendSectionsView extends StatelessWidget {
kind: RecommendSectionKind.newReleases,
source: source,
);
return AppPullToRefresh(
key: const Key('recommend-sections-refresh'),
onRefresh: () async {
await Future.wait([feedController.refreshCurrent(), categories.load()]);
},
child: ListView(
key: const Key('recommend-sections-scroll'),
physics: AppPullToRefresh.physics,
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
children: [
return [
_section(
context,
l10n,
@@ -87,9 +116,97 @@ class RecommendSectionsView extends StatelessWidget {
).take(_sectionPreviewCount).toList(),
onMore: () => onMore(RecommendSectionKind.costume),
),
],
),
);
];
}
List<Widget> _remoteSections(
BuildContext context,
AppLocalizations l10n,
PlaylistController remote,
) {
if (!remote.loaded && remote.loading) {
return const [
SizedBox(
height: 240,
child: Center(
child: CircularProgressIndicator(
key: Key('recommend-playlists-loading'),
),
),
),
];
}
if (remote.items.isEmpty) {
return [
EmptyState(
key: const Key('recommend-playlists-empty'),
icon: Icons.video_library_outlined,
title: remote.error == null ? l10n.emptyContent : l10n.networkError,
actionLabel: l10n.retry,
onAction: remote.load,
),
];
}
final sections = <Widget>[];
for (final playlist in remote.items) {
if (sections.isNotEmpty) {
sections.add(const SizedBox(height: AppDimens.spaceXl));
}
sections.add(
_section(
context,
l10n,
key: playlist.id,
title: playlist.localizedName(
Localizations.localeOf(context).languageCode,
),
subtitle: playlist.localizedDescription(
Localizations.localeOf(context).languageCode,
),
dramas: playlist.dramas.take(_sectionPreviewCount).toList(),
onMore: () => onOpenPlaylist?.call(playlist),
),
);
}
if (remote.loadingMore) {
sections.add(
const Padding(
padding: EdgeInsets.symmetric(vertical: AppDimens.spaceMd),
child: Center(
child: CircularProgressIndicator(
key: Key('recommend-playlists-more'),
),
),
),
);
} else if (!remote.hasMore) {
sections.add(
Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
),
);
}
return sections;
}
bool _onPlaylistScroll(
ScrollNotification notification,
PlaylistController remote,
) {
if (notification.depth != 0) return false;
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification) {
return false;
}
remote.loadMore();
return false;
}
Widget _section(
@@ -145,6 +145,8 @@ class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
],
PagedListFooter(
loading: controller.loadingMore,
hasMore: controller.hasMore,
hasItems: controller.records.isNotEmpty,
errorMessage: controller.loadMoreError == null
? null
: errorText(l10n, controller.loadMoreError, l10n.progressError),
@@ -52,9 +52,10 @@ class WatchRecordCard extends StatelessWidget {
final episodeLabel = episodeNumber > 0
? l10n.episodeLabel(record.episodeNumber)
: l10n.episodeUnavailable;
final title = record.displayTitle.isEmpty
? episodeLabel
: record.displayTitle;
final titleText = record.localizedDisplayTitle(
Localizations.localeOf(context).languageCode,
);
final title = titleText.isEmpty ? episodeLabel : titleText;
return _card(
onTap: onOpen,
child: Stack(