feat(app): 完善播放协议搜索与空状态

This commit is contained in:
Zhou Weidong committed 2026-10-23 12:38:47 +08:00
1 parent 671e0ce143
commit ef29fc5f15
85 files changed
+2976 -768

No files matched your search

@@ -0,0 +1,106 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_dimens.dart';
import '../../l10n/app_localizations.dart';
import 'account_deactivate_logic.dart';
/// 注销原因:固定选项在标题下换行排列,补充说明留在输入框内。
class DeactivateReasonField extends StatelessWidget {
const DeactivateReasonField({
super.key,
required this.controller,
required this.onChanged,
});
final TextEditingController controller;
final VoidCallback onChanged;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final options = _options(l10n);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.accountDeactivateReason,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: AppDimens.listTitle,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: AppDimens.spaceSm),
Wrap(
spacing: AppDimens.spaceSm,
runSpacing: AppDimens.spaceSm,
children: [
for (var index = 0; index < options.length; index++)
_chip(options[index], index, options),
],
),
const SizedBox(height: AppDimens.spaceMd),
TextField(
key: const Key('account-deactivate-reason'),
controller: controller,
maxLength: AccountDeactivateLogic.maxReasonLength,
minLines: 3,
maxLines: 4,
textAlignVertical: TextAlignVertical.top,
onChanged: (_) => onChanged(),
decoration: InputDecoration(
hintText: l10n.accountDeactivateReasonHint,
floatingLabelBehavior: FloatingLabelBehavior.never,
alignLabelWithHint: true,
contentPadding: const EdgeInsets.all(AppDimens.cardPadding),
),
),
],
);
}
Widget _chip(_ReasonOption option, int index, List<_ReasonOption> options) {
final selected = option.custom
? _customSelected(options)
: controller.text == option.label;
return ChoiceChip(
key: Key('account-deactivate-reason-$index'),
label: Text(option.label),
selected: selected,
onSelected: (_) => _select(option),
);
}
bool _customSelected(List<_ReasonOption> options) {
final text = controller.text.trim();
if (text.isEmpty) return false;
return options
.where((item) => !item.custom)
.every((item) => item.label != text);
}
void _select(_ReasonOption option) {
controller.text = option.custom ? '' : option.label;
controller.selection = TextSelection.collapsed(
offset: controller.text.length,
);
onChanged();
}
List<_ReasonOption> _options(AppLocalizations l10n) => [
_ReasonOption(l10n.accountDeactivateReasonUnused),
_ReasonOption(l10n.accountDeactivateReasonContent),
_ReasonOption(l10n.accountDeactivateReasonPrivacy),
_ReasonOption(l10n.accountDeactivateReasonOther, custom: true),
];
}
class _ReasonOption {
const _ReasonOption(this.label, {this.custom = false});
final String label;
final bool custom;
}
+99 -112
View File
@@ -10,132 +10,119 @@ import 'account_devices_page.dart';
import 'account_export_page.dart';
import 'account_profile_page.dart';
const _accountTitleWidth = 64.0;
/// 我的页账号入口卡;只在登录态由父页面展示。
/// 设置页账号入口,登录后按列表展示。
class AccountEntryCard extends StatelessWidget {
const AccountEntryCard({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final rows = <_AccountRow>[
_AccountRow(
key: const Key('mine-account-profile'),
icon: Icons.person_outline_rounded,
title: l10n.accountProfile,
page: const AccountProfilePage(),
),
_AccountRow(
key: const Key('mine-account-devices'),
icon: Icons.devices_other_rounded,
title: l10n.accountDevices,
page: const AccountDevicesPage(),
),
_AccountRow(
key: const Key('mine-account-export'),
icon: Icons.file_download_outlined,
title: l10n.accountDataExport,
page: const AccountExportPage(),
),
_AccountRow(
key: const Key('mine-account-deactivate'),
icon: Icons.person_remove_outlined,
title: l10n.accountDeactivate,
page: const AccountDeactivatePage(),
),
];
return Material(
key: const Key('mine-account-card'),
color: AppColors.card,
borderRadius: BorderRadius.circular(16),
borderRadius: BorderRadius.circular(AppDimens.cardRadius),
clipBehavior: Clip.antiAlias,
child: SizedBox(
height: AppDimens.accountCardHeight,
child: Row(
children: [
SizedBox(
width: _accountTitleWidth,
child: Padding(
padding: const EdgeInsets.only(left: 12),
child: Text(
l10n.accountCenter,
style: const TextStyle(
fontSize: AppDimens.caption,
fontWeight: FontWeight.w800,
),
),
),
),
const VerticalDivider(
width: 1,
color: AppColors.outlineVariantDark,
),
Expanded(
child: Row(
children: [
_entry(
context,
key: const Key('mine-account-profile'),
icon: Icons.person_outline_rounded,
title: l10n.accountProfile,
page: const AccountProfilePage(),
divider: true,
),
_entry(
context,
key: const Key('mine-account-devices'),
icon: Icons.devices_other_rounded,
title: l10n.accountDevices,
page: const AccountDevicesPage(),
divider: true,
),
_entry(
context,
key: const Key('mine-account-export'),
icon: Icons.file_download_outlined,
title: l10n.accountDataExport,
page: const AccountExportPage(),
divider: true,
),
_entry(
context,
key: const Key('mine-account-deactivate'),
icon: Icons.person_remove_outlined,
title: l10n.accountDeactivate,
page: const AccountDeactivatePage(),
divider: false,
),
],
),
),
],
),
),
);
}
Widget _entry(
BuildContext context, {
required Key key,
required IconData icon,
required String title,
required Widget page,
required bool divider,
}) {
return Expanded(
child: Row(
child: Column(
children: [
Expanded(
child: InkWell(
key: key,
onTap: () => Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => page)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
icon,
color: AppColors.blueSoft,
size: AppDimens.accountIcon,
),
const SizedBox(height: 2),
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: AppDimens.accountLabel,
height: 1.15,
),
),
],
for (var index = 0; index < rows.length; index++) ...[
if (index > 0)
const Divider(
height: AppDimens.mineGridDividerWidth,
thickness: AppDimens.mineGridDividerWidth,
color: AppColors.outlineVariantDark,
),
),
),
if (divider)
const VerticalDivider(
width: 1,
color: AppColors.outlineVariantDark,
),
_AccountListTile(row: rows[index]),
],
],
),
);
}
}
class _AccountRow {
const _AccountRow({
required this.key,
required this.icon,
required this.title,
required this.page,
});
final Key key;
final IconData icon;
final String title;
final Widget page;
}
class _AccountListTile extends StatelessWidget {
const _AccountListTile({required this.row});
final _AccountRow row;
@override
Widget build(BuildContext context) {
return InkWell(
key: row.key,
onTap: () => Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => row.page)),
child: SizedBox(
height: AppDimens.mineMoreRowHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppDimens.spaceLg),
child: Row(
children: [
Icon(
row.icon,
color: AppColors.blueSoft,
size: AppDimens.accountIcon,
),
const SizedBox(width: AppDimens.spaceMd),
Expanded(
child: Text(
row.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: AppDimens.listTitle,
),
),
),
const Icon(
Icons.chevron_right_rounded,
color: AppColors.textSecondary,
size: AppDimens.accountIcon,
),
],
),
),
),
);
}
}
-1
View File
@@ -336,7 +336,6 @@ class _AuthBrand extends StatelessWidget {
key: const Key('auth-brand-mark'),
size: compact ? _compactBrandMarkSize : _brandMarkSize,
radius: compact ? _compactBrandMarkRadius : _brandMarkRadius,
iconSize: compact ? _compactBrandIconSize : _brandIconSize,
);
Widget _brandCopy(BuildContext context, {required bool centered}) => Column(
+75
View File
@@ -0,0 +1,75 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../core/legal/legal_opener.dart';
import '../../core/legal/legal_page.dart';
import '../../core/theme/app_colors.dart';
import '../../l10n/app_localizations.dart';
const double _legalFontSize = 12;
/// 登录页底部的协议入口。点用户协议或隐私政策会打开对应语言的页面。
class AuthLegalLinks extends StatefulWidget {
const AuthLegalLinks({super.key, this.open});
/// 测试时可替换真正的跳转。
final Future<void> Function(String url)? open;
@override
State<AuthLegalLinks> createState() => _AuthLegalLinksState();
}
class _AuthLegalLinksState extends State<AuthLegalLinks> {
late final TapGestureRecognizer _termsTap = TapGestureRecognizer()
..onTap = () => _open(legalTermsPath);
late final TapGestureRecognizer _privacyTap = TapGestureRecognizer()
..onTap = () => _open(legalPrivacyPath);
@override
void dispose() {
_termsTap.dispose();
_privacyTap.dispose();
super.dispose();
}
void _open(String path) {
final url = legalPageUrl(path, Localizations.localeOf(context));
final custom = widget.open;
if (custom != null) {
unawaited(custom(url));
return;
}
unawaited(openLegalUrlOrNotify(context, url));
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final muted = TextStyle(color: AppColors.muted, fontSize: _legalFontSize, height: 1.6);
final link = muted.copyWith(color: AppColors.blue);
return Text.rich(
TextSpan(
style: muted,
children: [
TextSpan(text: l10n.authLegalLead),
const TextSpan(text: ' '),
TextSpan(text: l10n.authTerms, style: link, recognizer: _termsTap),
const TextSpan(text: ' '),
TextSpan(text: l10n.authLegalJoin),
const TextSpan(text: ' '),
TextSpan(
text: l10n.authPrivacy,
style: link,
recognizer: _privacyTap,
),
],
),
key: const Key('auth-legal'),
textAlign: TextAlign.center,
);
}
}
+14 -37
View File
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/data/remote/api_client.dart';
import '../../core/formatting/error_text.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/platform/haptics.dart';
import '../../core/platform/keyboard_inset.dart';
@@ -15,6 +16,7 @@ import '../../core/theme/app_theme.dart';
import '../../core/widgets/centered_toast.dart';
import '../../core/widgets/subpage_header.dart';
import '../../l10n/app_localizations.dart';
import 'auth_legal_links.dart';
import 'auth_logic.dart';
import 'phone_auth_sheet.dart';
@@ -26,8 +28,8 @@ const double _brandMarkSize = 72;
const double _compactBrandMarkSize = 48;
const double _brandMarkRadius = 20;
const double _compactBrandMarkRadius = 14;
const double _brandIconSize = 36;
const double _compactBrandIconSize = 26;
const double _landingLogoTopGap = 28;
const String _appLogoAsset = 'assets/icon/fruitshorts.png';
const double _contentMaxWidth = 440;
// Auth keeps its approved 20px card silhouette.
const double _cardRadius = AppDimens.authCardRadius;
@@ -58,31 +60,15 @@ Widget _brandMarkWidget({
Key? key,
required double size,
required double radius,
required double iconSize,
}) {
return Container(
return ClipRRect(
key: key,
width: size,
height: size,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(radius),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [AppColors.blue, AppColors.secondary],
),
boxShadow: [
BoxShadow(
color: AppColors.blue.withValues(alpha: 0.24),
blurRadius: 20,
offset: const Offset(0, 8),
),
],
),
child: Icon(
Icons.play_arrow_rounded,
color: AppColors.onPrimary,
size: iconSize,
borderRadius: BorderRadius.circular(radius),
child: Image.asset(
_appLogoAsset,
width: size,
height: size,
fit: BoxFit.cover,
),
);
}
@@ -257,7 +243,7 @@ class _AuthPageState extends State<AuthPage> {
if (!mounted) return;
Navigator.of(context).maybePop();
} on ApiException catch (error) {
failureMessage = error.message;
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
@@ -431,12 +417,12 @@ class _AuthPageState extends State<AuthPage> {
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: _landingLogoTopGap),
Center(
child: _brandMarkWidget(
key: const Key('auth-brand-logo'),
size: _brandMarkSize,
radius: _brandMarkRadius,
iconSize: _brandIconSize,
),
),
const SizedBox(height: 16),
@@ -473,16 +459,7 @@ class _AuthPageState extends State<AuthPage> {
onTap: () => setState(() => _emailEntryOpen = true),
),
const SizedBox(height: 18),
Text(
l10n.authLegal,
key: const Key('auth-legal'),
textAlign: TextAlign.center,
style: const TextStyle(
color: AppColors.muted,
fontSize: 9,
height: 1.6,
),
),
const AuthLegalLinks(),
],
);
+61 -26
View File
@@ -20,6 +20,11 @@ import 'discover_binding.dart';
import 'discover_logic.dart';
import 'widgets/search_result_card.dart';
const double _clearHit = 20;
const double _clearIconSize = 16;
const double _clearEndGap = 10;
const double _loadingInset = 2;
class SearchPage extends StatefulWidget {
const SearchPage({super.key});
@@ -119,11 +124,10 @@ class _SearchPageState extends State<SearchPage> {
}
Widget _field(AppLocalizations l10n) {
final hasText = _logic.search.text.isNotEmpty;
return Container(
key: const Key('search-field'),
height: AppDimens.searchHeight,
padding: const EdgeInsets.symmetric(horizontal: AppDimens.spaceMd),
padding: const EdgeInsets.only(left: AppDimens.spaceMd),
decoration: BoxDecoration(
color: AppColors.contentSurface,
borderRadius: BorderRadius.circular(AppDimens.searchRadius),
@@ -143,7 +147,9 @@ class _SearchPageState extends State<SearchPage> {
focusNode: _logic.searchFocus,
autofocus: true,
onChanged: (_) => _logic.onSearchChanged(),
onTapOutside: (_) => _logic.searchFocus.unfocus(),
textInputAction: TextInputAction.search,
textAlignVertical: TextAlignVertical.center,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 14,
@@ -163,35 +169,64 @@ class _SearchPageState extends State<SearchPage> {
scrollPadding: EdgeInsets.zero,
),
),
if (_logic.searchLoading)
const SizedBox.square(
dimension: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.textPrimary,
),
)
else if (hasText)
IconButton(
key: const Key('search-clear'),
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(width: 24, height: 24),
onPressed: () {
_logic.search.clear();
_logic.onSearchChanged();
_logic.searchFocus.requestFocus();
},
icon: const Icon(
Icons.close_rounded,
color: AppColors.textSecondary,
size: 16,
),
),
_fieldTrailing(),
],
),
);
}
/// 有内容时把清除按钮放在输入框内部右侧,并留出一点边距。
/// 刷新时不拿转圈替换叉号,避免宽度变化把按钮抖开。
Widget _fieldTrailing() {
final hasText = _logic.search.text.isNotEmpty;
if (!hasText && !_logic.searchLoading) {
return const SizedBox(width: AppDimens.spaceMd);
}
return SizedBox(
width: _clearHit + _clearEndGap,
child: Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(right: _clearEndGap),
child: hasText ? _clearButton() : _loadingMark(),
),
),
);
}
Widget _clearButton() {
return GestureDetector(
key: const Key('search-clear'),
behavior: HitTestBehavior.opaque,
onTap: () {
_logic.search.clear();
_logic.onSearchChanged();
_logic.searchFocus.requestFocus();
},
child: const SizedBox.square(
dimension: _clearHit,
child: Icon(
Icons.close_rounded,
color: AppColors.textSecondary,
size: _clearIconSize,
),
),
);
}
Widget _loadingMark() {
return const SizedBox.square(
dimension: _clearHit,
child: Padding(
padding: EdgeInsets.all(_loadingInset),
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.textPrimary,
),
),
);
}
Widget _body(AppLocalizations l10n) {
if (!_logic.hasSearchQuery) {
return _stateScroll(
+228
View File
@@ -0,0 +1,228 @@
// Author: fruit.com.cn
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../core/data/services/favorite_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../l10n/app_localizations.dart';
enum FollowingTab { favorites, history }
/// 编辑底栏的全选与取消动作。
class FollowingEditActions {
const FollowingEditActions({
required this.onToggleAll,
required this.onRemove,
});
final void Function(Set<String> ids) onToggleAll;
final VoidCallback onRemove;
}
const double _barHeight = 48;
const double _barHorizontal = 16;
const double _barFontSize = 13;
const double _barButtonHeight = 30;
const double _removeDialogButtonHeight = 32;
const double _removeDialogRadius = 6;
const double _removeDialogBottomInset = 8;
/// 播放历史移除确认。只把移除按钮压矮。
Future<bool> confirmHistoryRemove(BuildContext context) async {
final l10n = AppLocalizations.of(context)!;
return await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
actionsPadding: const EdgeInsets.fromLTRB(
24,
0,
16,
_removeDialogBottomInset,
),
content: Text(l10n.confirmRemove),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(l10n.cancel),
),
FilledButton(
style: FilledButton.styleFrom(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: const Size(0, _removeDialogButtonHeight),
padding: const EdgeInsets.symmetric(horizontal: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(_removeDialogRadius),
),
),
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(l10n.remove),
),
],
),
) ??
false;
}
/// 确认后返回是否取消已选追剧。
Future<bool> confirmCancelFollowing(BuildContext context) async {
final l10n = AppLocalizations.of(context)!;
return await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
content: Text(l10n.confirmCancelFollowing),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(l10n.cancelFollowing),
),
],
),
) ??
false;
}
/// 只在追剧编辑中显示底栏。
class FollowingEditSlot extends StatelessWidget {
const FollowingEditSlot({
super.key,
required this.tab,
required this.editing,
required this.favorites,
required this.selected,
required this.actions,
});
final ValueListenable<FollowingTab> tab;
final ValueListenable<bool> editing;
final FavoriteController favorites;
final ValueListenable<Set<String>> selected;
final FollowingEditActions actions;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<FollowingTab>(
valueListenable: tab,
builder: (context, current, _) {
return ValueListenableBuilder<bool>(
valueListenable: editing,
builder: (context, isEditing, _) {
if (!isEditing || current != FollowingTab.favorites) {
return const SizedBox.shrink();
}
return _bar();
},
);
},
);
}
Widget _bar() {
return ListenableBuilder(
listenable: favorites,
builder: (context, _) {
return ValueListenableBuilder<Set<String>>(
valueListenable: selected,
builder: (context, picked, _) {
final ids = favorites.cards.map((drama) => drama.id).toSet();
return FollowingEditBar(
allSelected: ids.isNotEmpty && ids.every(picked.contains),
canRemove: picked.isNotEmpty,
onToggleAll: () => actions.onToggleAll(ids),
onRemove: actions.onRemove,
);
},
);
},
);
}
}
/// 追剧编辑底栏:全选,以及取消已选追剧。
class FollowingEditBar extends StatelessWidget {
const FollowingEditBar({
super.key,
required this.allSelected,
required this.canRemove,
required this.onToggleAll,
required this.onRemove,
});
final bool allSelected;
final bool canRemove;
final VoidCallback onToggleAll;
final VoidCallback onRemove;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Material(
key: const Key('following-edit-bar'),
color: AppColors.card,
child: SafeArea(
top: false,
child: SizedBox(
height: _barHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: _barHorizontal),
child: Row(
children: [
TextButton(
key: const Key('following-select-all'),
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: const Size(0, _barButtonHeight),
padding: const EdgeInsets.symmetric(horizontal: 4),
textStyle: const TextStyle(
fontSize: _barFontSize,
fontWeight: FontWeight.w500,
),
),
onPressed: onToggleAll,
child: Text(
allSelected ? l10n.deselectAll : l10n.selectAll,
style: const TextStyle(
fontSize: _barFontSize,
fontWeight: FontWeight.w500,
),
),
),
const Spacer(),
FilledButton(
key: const Key('following-cancel-follow'),
style: FilledButton.styleFrom(
visualDensity: VisualDensity.compact,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: const Size(0, _removeDialogButtonHeight),
padding: const EdgeInsets.symmetric(horizontal: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(_removeDialogRadius),
),
textStyle: const TextStyle(
fontSize: _barFontSize,
fontWeight: FontWeight.w600,
),
),
onPressed: canRemove ? onRemove : null,
child: Text(
l10n.cancelFollowing,
style: const TextStyle(
fontSize: _barFontSize,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,118 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../core/data/services/favorite_controller.dart';
import '../../core/formatting/error_text.dart';
import '../../l10n/app_localizations.dart';
import '../player/open_player.dart';
import 'following_grid_card.dart';
import 'following_paged_grid.dart';
/// 追剧编辑中的选中状态。
class FollowingFavoriteSelection {
const FollowingFavoriteSelection({
required this.editing,
required this.selected,
required this.onToggle,
});
final ValueListenable<bool> editing;
final ValueListenable<Set<String>> selected;
final ValueChanged<String> onToggle;
}
/// 追剧列表。编辑时点卡片只切换选中,不进入播放。
class FollowingFavoritesGrid extends StatelessWidget {
const FollowingFavoritesGrid({
super.key,
required this.controller,
required this.selection,
required this.scrollController,
required this.onGoHome,
});
final FavoriteController controller;
final FollowingFavoriteSelection selection;
final ScrollController scrollController;
final VoidCallback onGoHome;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: selection.editing,
builder: (context, isEditing, _) {
return ValueListenableBuilder<Set<String>>(
valueListenable: selection.selected,
builder: (context, picked, _) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) => _grid(context, isEditing, picked),
);
},
);
},
);
}
Widget _grid(BuildContext context, bool isEditing, Set<String> picked) {
final l10n = AppLocalizations.of(context)!;
final extra = isEditing ? 0 : 1;
return FollowingPagedGrid(
key: const Key('following-favorites-grid'),
scrollController: scrollController,
loading: controller.loading,
loadingMore: controller.loadingMore,
hasMore: controller.hasMore,
hasItems: controller.cards.isNotEmpty,
showInitialLoading: false,
errorMessage: controller.error == null
? null
: errorText(l10n, controller.error, l10n.favoritesError),
loadMoreError: controller.loadMoreError == null
? null
: errorText(l10n, controller.loadMoreError, l10n.favoritesError),
onRefresh: controller.load,
onLoadMore: controller.loadMore,
itemCount: controller.cards.length + extra,
empty: const SizedBox.shrink(),
itemBuilder: (context, index) => _item(context, index, isEditing, picked),
);
}
Widget _item(
BuildContext context,
int index,
bool isEditing,
Set<String> picked,
) {
if (index == controller.cards.length) {
return FollowingAddCard(onTap: onGoHome);
}
final l10n = AppLocalizations.of(context)!;
final drama = controller.cards[index];
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
return FollowingGridCard(
dramaId: drama.id,
title: drama.title,
posterUrl: drama.posterUrl,
viewCount: drama.viewCount,
editing: isEditing,
selected: isEditing ? picked.contains(drama.id) : null,
subtitle: l10n.favoriteEpisodeProgress(episode, drama.episodeCount),
onTap: () => _openOrToggle(context, drama.id, isEditing),
);
}
void _openOrToggle(BuildContext context, String dramaId, bool isEditing) {
if (isEditing) {
selection.onToggle(dramaId);
return;
}
final drama = controller.cards.firstWhere((item) => item.id == dramaId);
unawaited(playDramaFromCatalog(context, drama));
}
}
+46 -1
View File
@@ -7,6 +7,11 @@ import '../../core/theme/app_dimens.dart';
import '../../core/widgets/cover_play_count.dart';
import '../../core/widgets/remote_image.dart';
const double _selectMarkSize = 22;
const double _selectMarkInset = 6;
const double _selectMarkIconSize = 16;
const double _selectBorderWidth = 1.5;
class FollowingGridCard extends StatelessWidget {
const FollowingGridCard({
super.key,
@@ -18,6 +23,7 @@ class FollowingGridCard extends StatelessWidget {
required this.onTap,
this.progress,
this.editing = false,
this.selected,
this.onRemove,
});
@@ -29,6 +35,7 @@ class FollowingGridCard extends StatelessWidget {
final VoidCallback onTap;
final double? progress;
final bool editing;
final bool? selected;
final VoidCallback? onRemove;
@override
@@ -59,7 +66,16 @@ class FollowingGridCard extends StatelessWidget {
),
),
),
if (editing)
if (selected != null)
Positioned(
top: _selectMarkInset,
right: _selectMarkInset,
child: _SelectMark(
key: Key('following-select-$dramaId'),
selected: selected!,
),
)
else if (editing)
Positioned(
top: -2,
right: -2,
@@ -141,6 +157,35 @@ class FollowingGridCard extends StatelessWidget {
}
}
class _SelectMark extends StatelessWidget {
const _SelectMark({super.key, required this.selected});
final bool selected;
@override
Widget build(BuildContext context) {
return Container(
width: _selectMarkSize,
height: _selectMarkSize,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: selected ? AppColors.blue : AppColors.transparent,
border: Border.all(
color: selected ? AppColors.blue : AppColors.textPrimary,
width: _selectBorderWidth,
),
),
child: selected
? const Icon(
Icons.check_rounded,
size: _selectMarkIconSize,
color: AppColors.onPrimary,
)
: null,
);
}
}
class FollowingAddCard extends StatelessWidget {
const FollowingAddCard({super.key, required this.onTap});
+114 -143
View File
@@ -19,12 +19,14 @@ import '../../core/widgets/auth_gate.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../player/open_player.dart';
import 'following_grid_card.dart';
import 'following_edit_bar.dart';
import 'following_favorites_grid.dart';
import 'following_history_card.dart';
import 'following_keep_alive_tab.dart';
import 'following_paged_grid.dart';
enum FollowingTab { favorites, history }
const double _doneFontSize = 14;
const double _doneTextGap = 12;
class FollowingPage extends StatefulWidget {
const FollowingPage({
@@ -50,21 +52,33 @@ class _FollowingPageState extends State<FollowingPage> {
FollowingTab.favorites,
);
final ValueNotifier<bool> _editing = ValueNotifier(false);
final ValueNotifier<Set<String>> _selected = ValueNotifier({});
late final WatchRecordsController _history;
late final AuthController _auth;
bool _wasSignedIn = false;
@override
void initState() {
super.initState();
_auth = context.read<AuthController>();
_wasSignedIn = _auth.isSignedIn;
_auth.addListener(_onAuthChanged);
_history = WatchRecordsController(
history: context.read<WatchHistoryRepository>(),
catalog: context.read<CatalogRepository>(),
);
unawaited(_history.load());
if (_wasSignedIn) unawaited(_history.load());
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(widget.favoriteController.load());
});
}
void _onAuthChanged() {
final signedIn = _auth.isSignedIn;
if (signedIn && !_wasSignedIn) unawaited(_history.load());
_wasSignedIn = signedIn;
}
@override
void dispose() {
_pageController.dispose();
@@ -72,6 +86,8 @@ class _FollowingPageState extends State<FollowingPage> {
_historyScroll.dispose();
_tab.dispose();
_editing.dispose();
_selected.dispose();
_auth.removeListener(_onAuthChanged);
_history.dispose();
super.dispose();
}
@@ -106,12 +122,15 @@ class _FollowingPageState extends State<FollowingPage> {
onPageChanged: _onPageChanged,
children: [
FollowingKeepAliveTab(
child: _FavoritesGrid(
child: FollowingFavoritesGrid(
controller: widget.favoriteController,
editing: _editing,
selection: FollowingFavoriteSelection(
editing: _editing,
selected: _selected,
onToggle: _toggleDrama,
),
scrollController: _favoriteScroll,
onGoHome: widget.onGoHome,
onListEmptied: _exitEditingIfEmpty,
),
),
FollowingKeepAliveTab(
@@ -125,6 +144,17 @@ class _FollowingPageState extends State<FollowingPage> {
],
),
),
if (signedIn)
FollowingEditSlot(
tab: _tab,
editing: _editing,
favorites: widget.favoriteController,
selected: _selected,
actions: FollowingEditActions(
onToggleAll: _toggleAll,
onRemove: () => unawaited(_cancelSelected()),
),
),
],
),
),
@@ -147,36 +177,43 @@ class _FollowingPageState extends State<FollowingPage> {
builder: (context, editing, _) {
return Row(
children: [
_tabButton(
FollowingTab.favorites,
l10n.followingTab,
'favorites',
selectedTab == FollowingTab.favorites,
Expanded(
child: Row(
children: [
Flexible(
fit: FlexFit.loose,
child: _tabButton(
FollowingTab.favorites,
l10n.followingTab,
'favorites',
selectedTab == FollowingTab.favorites,
),
),
const SizedBox(width: AppDimens.followingTabGap),
Flexible(
fit: FlexFit.loose,
child: _tabButton(
FollowingTab.history,
l10n.watchHistory,
'history',
selectedTab == FollowingTab.history,
),
),
],
),
),
const SizedBox(width: AppDimens.followingTabGap),
_tabButton(
FollowingTab.history,
l10n.watchHistory,
'history',
selectedTab == FollowingTab.history,
),
const Spacer(),
if (editing)
SizedBox(
width: AppDimens.followingEditHitSize,
height: AppDimens.followingEditHitSize,
child: InkWell(
key: const Key('following-edit'),
onTap: _toggleEditing,
child: Align(
alignment: Alignment.centerRight,
child: Text(
l10n.done,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: AppDimens.followingTabFont,
fontWeight: FontWeight.w600,
),
InkWell(
key: const Key('following-edit'),
onTap: _toggleEditing,
child: Padding(
padding: const EdgeInsets.only(left: _doneTextGap),
child: Text(
l10n.done,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: _doneFontSize,
fontWeight: FontWeight.w500,
),
),
),
@@ -223,7 +260,9 @@ class _FollowingPageState extends State<FollowingPage> {
onTap: () => _selectTab(tab),
child: SizedBox(
height: AppDimens.followingHeaderHeight,
child: Center(
child: Align(
alignment: Alignment.centerLeft,
widthFactor: 1,
child: AnimatedDefaultTextStyle(
duration: AppDimens.followingTabAnimationDuration,
style: TextStyle(
@@ -233,7 +272,7 @@ class _FollowingPageState extends State<FollowingPage> {
fontSize: AppDimens.followingTabFont,
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
),
child: Text(label, maxLines: 1),
child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
),
),
),
@@ -241,7 +280,7 @@ class _FollowingPageState extends State<FollowingPage> {
}
void _selectTab(FollowingTab tab) {
_editing.value = false;
_leaveEditing();
_tab.value = tab;
if (_pageController.hasClients) {
unawaited(
@@ -256,99 +295,50 @@ class _FollowingPageState extends State<FollowingPage> {
void _onPageChanged(int index) {
final tab = FollowingTab.values[index];
_editing.value = false;
_leaveEditing();
_tab.value = tab;
if (tab == FollowingTab.history && _auth.isSignedIn) {
unawaited(_history.load());
}
}
void _toggleEditing() {
_editing.value = !_editing.value;
if (!_editing.value) _selected.value = {};
}
void _leaveEditing() {
_editing.value = false;
_selected.value = {};
}
void _toggleDrama(String id) {
final next = {..._selected.value};
if (!next.add(id)) next.remove(id);
_selected.value = next;
}
void _toggleAll(Set<String> ids) {
final picked = _selected.value;
final all = ids.isNotEmpty && ids.every(picked.contains);
_selected.value = all ? {} : ids;
}
Future<void> _cancelSelected() async {
final ids = _selected.value.toList();
if (ids.isEmpty || !mounted || !await confirmCancelFollowing(context)) {
return;
}
if (!mounted) return;
final removed = await widget.favoriteController.removeMany(ids);
if (!removed || !mounted) return;
_selected.value = {};
if (widget.favoriteController.cards.isEmpty) _editing.value = false;
}
void _exitEditingIfEmpty() => _editing.value = false;
}
class _FavoritesGrid extends StatelessWidget {
const _FavoritesGrid({
required this.controller,
required this.editing,
required this.scrollController,
required this.onGoHome,
required this.onListEmptied,
});
final FavoriteController controller;
final ValueListenable<bool> editing;
final ScrollController scrollController;
final VoidCallback onGoHome;
final VoidCallback onListEmptied;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: editing,
builder: (context, isEditing, _) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
final l10n = AppLocalizations.of(context)!;
return FollowingPagedGrid(
key: const Key('following-favorites-grid'),
scrollController: scrollController,
loading: controller.loading,
loadingMore: controller.loadingMore,
hasMore: controller.hasMore,
hasItems: controller.cards.isNotEmpty,
showInitialLoading: false,
errorMessage: controller.error == null
? null
: errorText(l10n, controller.error, l10n.favoritesError),
loadMoreError: controller.loadMoreError == null
? null
: errorText(
l10n,
controller.loadMoreError,
l10n.favoritesError,
),
onRefresh: controller.load,
onLoadMore: controller.loadMore,
itemCount: controller.cards.length + 1,
empty: const SizedBox.shrink(),
itemBuilder: (context, index) {
if (index == controller.cards.length) {
return FollowingAddCard(onTap: onGoHome);
}
final drama = controller.cards[index];
final episode = drama.episodes.isEmpty
? 1
: drama.episodes.first.number;
return FollowingGridCard(
dramaId: drama.id,
title: drama.title,
posterUrl: drama.posterUrl,
viewCount: drama.viewCount,
editing: isEditing,
subtitle: l10n.favoriteEpisodeProgress(
episode,
drama.episodeCount,
),
onTap: () => unawaited(playDramaFromCatalog(context, drama)),
onRemove: () async {
if (await _confirmRemove(context) &&
await controller.remove(drama.id) &&
controller.cards.isEmpty) {
onListEmptied();
}
},
);
},
);
},
);
},
);
}
}
class _HistoryList extends StatelessWidget {
const _HistoryList({
required this.controller,
@@ -415,7 +405,9 @@ class _HistoryList extends StatelessWidget {
title: _historyTitle(l10n, record),
posterUrl: record.displayCover,
viewCount:
record.drama?.viewCount ?? record.progress.playCount,
record.progress.viewCount ??
record.drama?.viewCount ??
record.progress.playCount,
progress: hasProgress ? progress : null,
progressLabel: hasProgress
? l10n.watchedPercent(watchedPercent)
@@ -425,7 +417,7 @@ class _HistoryList extends StatelessWidget {
onTap: openRecord,
onContinue: openRecord,
onRemove: () async {
if (await _confirmRemove(context) &&
if (await confirmHistoryRemove(context) &&
await controller.remove(record.dramaId) &&
controller.records.isEmpty) {
onListEmptied();
@@ -469,24 +461,3 @@ Future<void> _openHistory(
episodeId: record.progress.episodeId,
);
}
Future<bool> _confirmRemove(BuildContext context) async {
final l10n = AppLocalizations.of(context)!;
return await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
content: Text(l10n.confirmRemove),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(l10n.remove),
),
],
),
) ??
false;
}
+14 -8
View File
@@ -174,17 +174,21 @@ class _HomeTabsState extends State<_HomeTabs> {
}
Widget _body(BuildContext context) {
final pages = <Widget>[
_homeGrid(context),
_recommend(context),
FollowingPage(
onGoHome: () => logic.select(0),
favoriteController: context.read<FavoriteController>(),
historyRequest: logic.followingHistoryRequest,
),
_my(context),
];
return IndexedStack(
index: logic.tab,
children: [
_homeGrid(context),
_recommend(context),
FollowingPage(
onGoHome: () => logic.select(0),
favoriteController: context.read<FavoriteController>(),
historyRequest: logic.followingHistoryRequest,
),
_my(context),
for (var index = 0; index < pages.length; index++)
TickerMode(enabled: logic.tab == index, child: pages[index]),
],
);
}
@@ -206,6 +210,8 @@ class _HomeTabsState extends State<_HomeTabs> {
return RecommendPage(
feedController: widget.feedController,
active: logic.tab == 1,
videoOnly: logic.videoImmersive,
onImmersiveChanged: logic.onImmersiveChanged,
onSearch: () => _openSearch(context),
);
}
+3 -12
View File
@@ -207,7 +207,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
if (dramas.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: _emptyState(l10n, tab, tag),
child: _emptyState(l10n),
)
else
SliverPadding(
@@ -360,7 +360,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
}
}
Widget _emptyState(AppLocalizations l10n, HomePrimaryTab tab, String? tag) {
Widget _emptyState(AppLocalizations l10n) {
if (widget.feedController.lastError != null) {
return EmptyState(
key: const Key('home-grid-error'),
@@ -370,19 +370,10 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
onAction: () => unawaited(widget.feedController.refreshCurrent()),
);
}
final filtered =
tab == HomePrimaryTab.costume ||
tab == HomePrimaryTab.community ||
tag != null;
return EmptyState(
key: const Key('home-grid-empty'),
icon: Icons.movie_filter_outlined,
title: filtered ? l10n.homeGridFilterEmpty : l10n.noStories,
subtitle: filtered ? null : l10n.emptyHint,
actionLabel: filtered ? l10n.homeGridClearFilter : null,
onAction: filtered
? () => setState(() => _selectedTags[tab] = null)
: null,
title: l10n.emptyContent,
);
}
}
-2
View File
@@ -12,8 +12,6 @@ enum MineDestination {
wallet,
vip,
preferences,
works,
creatorCenter,
notices,
settings,
help,
+10 -73
View File
@@ -158,7 +158,10 @@ class _MyPageState extends State<MyPage> {
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.pageHorizontal,
),
child: MineHeader(onLogin: _openLogin, onEdit: _openEditActions),
child: MineHeader(
onLogin: _openLogin,
onEdit: () => _push(const AccountProfilePage()),
),
),
Padding(
padding: const EdgeInsets.symmetric(
@@ -202,7 +205,7 @@ class _MyPageState extends State<MyPage> {
horizontal: AppDimens.mineGridHorizontal,
),
child: MineMoreServices(
onCommonQuestions: () => _pushPlaceholder(MinePlaceholderKind.help),
onCommonQuestions: _pushPlaceholder,
onAbout: () => _push(const MineAboutPage()),
),
),
@@ -222,16 +225,12 @@ class _MyPageState extends State<MyPage> {
_openVip();
case MineDestination.preferences:
_push(const FilterPage());
case MineDestination.works:
_pushPlaceholder(MinePlaceholderKind.works);
case MineDestination.creatorCenter:
_pushPlaceholder(MinePlaceholderKind.creator);
case MineDestination.notices:
_push(const NoticesPage());
case MineDestination.settings:
_push(const SettingsPage());
case MineDestination.help:
_pushPlaceholder(MinePlaceholderKind.help);
_pushPlaceholder();
}
}
@@ -248,66 +247,12 @@ class _MyPageState extends State<MyPage> {
_push(const WatchRecordsPage());
}
Future<void> _openEditActions() async {
final selected = await showModalBottomSheet<String>(
context: context,
backgroundColor: AppColors.transparent,
showDragHandle: false,
builder: (sheetContext) => Material(
color: AppColors.mineCard,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(AppDimens.mineCardRadius),
),
clipBehavior: Clip.antiAlias,
child: SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
key: const Key('mine-edit-profile'),
title: Text(AppLocalizations.of(sheetContext)!.accountProfile),
onTap: () => Navigator.pop(sheetContext, 'profile'),
),
ListTile(
key: const Key('mine-edit-works'),
title: Text(AppLocalizations.of(sheetContext)!.myWorks),
onTap: () => Navigator.pop(sheetContext, 'works'),
),
ListTile(
key: const Key('mine-edit-creator'),
title: Text(AppLocalizations.of(sheetContext)!.creatorCenter),
onTap: () => Navigator.pop(sheetContext, 'creator'),
),
ListTile(
key: const Key('mine-edit-notices'),
title: Text(AppLocalizations.of(sheetContext)!.notices),
onTap: () => Navigator.pop(sheetContext, 'notices'),
),
],
),
),
),
);
if (!mounted || selected == null) return;
switch (selected) {
case 'profile':
_push(const AccountProfilePage());
case 'works':
_pushPlaceholder(MinePlaceholderKind.works);
case 'creator':
_pushPlaceholder(MinePlaceholderKind.creator);
case 'notices':
_push(const NoticesPage());
}
}
void _push(Widget page) {
Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => page));
}
void _pushPlaceholder(MinePlaceholderKind kind) {
_push(_MinePlaceholderPage(kind: kind));
void _pushPlaceholder() {
_push(const _MinePlaceholderPage());
}
Future<void> _openProtected(Widget page) async {
@@ -431,21 +376,13 @@ class _LanguageSheet extends StatelessWidget {
}
}
enum MinePlaceholderKind { works, creator, help }
class _MinePlaceholderPage extends StatelessWidget {
const _MinePlaceholderPage({required this.kind});
final MinePlaceholderKind kind;
const _MinePlaceholderPage();
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final title = switch (kind) {
MinePlaceholderKind.works => l10n.myWorks,
MinePlaceholderKind.creator => l10n.creatorCenter,
MinePlaceholderKind.help => l10n.helpFeedback,
};
final title = l10n.helpFeedback;
return PlainPageScaffold(
pageKey: const Key('mine-placeholder-page'),
backKey: const Key('mine-placeholder-back'),
+1 -1
View File
@@ -14,7 +14,7 @@ import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
const double _buttonHeight = 34;
const double _buttonRadius = 20;
const double _buttonRadius = 6;
/// 「我的」页用户区。
class MineHeader extends StatelessWidget {
+8 -1
View File
@@ -209,7 +209,14 @@ class MineMenuList extends StatelessWidget {
label: l10n.settings,
onTap: () => onOpen(MineDestination.settings),
),
_cell(index: 7),
_cell(
index: 7,
actionKey: const Key('mine-notices'),
icon: Icons.notifications_none_rounded,
iconColor: AppColors.mineIconNotices,
label: l10n.notices,
onTap: () => onOpen(MineDestination.notices),
),
],
),
],
+83 -3
View File
@@ -3,6 +3,7 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter/scheduler.dart';
import 'package:provider/provider.dart';
@@ -88,6 +89,9 @@ class PlayerLogic extends ChangeNotifier {
String? blockedEpisodeId;
List<Episode> sessionEpisodes = const [];
List<String> qualities = const [];
List<PlayQualityTrack> qualityTracks = const [];
String selectedQuality = 'AUTO';
Duration? _qualitySeek;
int pageRequest = 0;
bool muted = false;
double playbackSpeed = 1.0;
@@ -426,6 +430,7 @@ class PlayerLogic extends ChangeNotifier {
blockedTicket = null;
blockedEpisodeId = null;
qualities = const [];
qualityTracks = const [];
sessionEpisodes[index] = episode.withVideoUrl(_fileUrl(localPath));
return true;
}
@@ -437,10 +442,18 @@ class PlayerLogic extends ChangeNotifier {
blockedTicket = null;
blockedEpisodeId = null;
qualities = ticket.qualities;
if (ticket.accessible && ticket.playUrl.isNotEmpty) {
qualityTracks = ticket.tracks;
final preferred = qualityPlayUrl(
quality: selectedQuality,
tracks: qualityTracks,
currentUrl: ticket.playUrl,
);
final playUrl = preferred ?? ticket.playUrl;
if (preferred == null) selectedQuality = 'AUTO';
if (ticket.accessible && playUrl.isNotEmpty) {
// 签名地址原样写回,不做任何拼接/改写(AppConfig.mediaUrl 只补 host)
sessionEpisodes[index] = episode.withVideoUrl(
ticket.playUrl,
playUrl,
likeCount: ticket.likeCount,
commentCount: ticket.commentCount,
thumbnailsUrl: ticket.thumbnailsUrl,
@@ -470,6 +483,64 @@ class PlayerLogic extends ChangeNotifier {
String _fileUrl(String path) =>
path.startsWith('file:') ? path : Uri.file(path).toString();
/// 切到指定清晰度。新片源出画后再替换,失败则继续播原来的。
Future<bool> selectQuality(String quality) async {
final index = session.currentIndex;
if (index < 0 || index >= sessionEpisodes.length) return false;
final current = sessionEpisodes[index];
final url = qualityPlayUrl(
quality: quality,
tracks: qualityTracks,
currentUrl: current.videoUrl,
);
if (url == null || url.isEmpty) return false;
if (selectedQuality.toUpperCase() == quality.toUpperCase() &&
current.videoUrl == url) {
return true;
}
final previousQuality = selectedQuality;
final active = session.active;
if (active is VideoPlayerPort && active.controller.value.isInitialized) {
_qualitySeek = active.controller.value.position;
}
selectedQuality = quality.toUpperCase();
sessionEpisodes[index] = current.withVideoUrl(url);
final switched = await session.replaceCurrent();
if (switched) {
if (isMounted()) notify();
return true;
}
_qualitySeek = null;
selectedQuality = previousQuality;
if (index < sessionEpisodes.length) {
sessionEpisodes[index] = current;
}
if (isMounted()) notify();
return false;
}
Future<void> _waitUntilFrameReady(VideoPlayerController controller) async {
if (controller.value.hasError) {
throw StateError('quality source failed');
}
if (!controller.value.isBuffering) return;
final done = Completer<void>();
void onChange() {
final value = controller.value;
if (done.isCompleted) return;
if (value.hasError || !value.isBuffering) done.complete();
}
controller.addListener(onChange);
try {
await done.future.timeout(const Duration(seconds: 4));
} finally {
controller.removeListener(onChange);
}
if (controller.value.hasError) {
throw StateError('quality source failed');
}
}
/// 重试当前集的票据(失败态的"重试"按钮)。
Future<void> retryTicket() async {
ticketError = null;
@@ -667,6 +738,15 @@ class PlayerLogic extends ChangeNotifier {
if (player is! VideoPlayerPort) return;
try {
await player.controller.setPlaybackSpeed(playbackSpeed);
final override = _qualitySeek;
_qualitySeek = null;
if (override != null && override > Duration.zero) {
await player.seekTo(
clampResumePosition(override, player.controller.value.duration),
);
await _waitUntilFrameReady(player.controller);
return;
}
await pendingWrite;
// 服务端每剧只记一条:只有"记录里的那一集"才定位,其它集从头播
if (resumePoint == null) await loadResumePoint();
@@ -689,7 +769,7 @@ class PlayerLogic extends ChangeNotifier {
);
}
} catch (_) {
// 续看位置取不到不影响播放:从头播。
// 续看或清晰度定位失败时仍用已初始化的播放器,不把切换判失败。
}
}
+44 -14
View File
@@ -363,7 +363,7 @@ class _PlayerPageState extends State<PlayerPage>
final lastDoubleTapAt = _lastDoubleTapAt;
return lastDoubleTapAt != null &&
DateTime.now().difference(lastDoubleTapAt) <
const Duration(milliseconds: 350);
const Duration(milliseconds: 500);
}
void _handleDoubleTapLike(
@@ -545,14 +545,18 @@ class _PlayerPageState extends State<PlayerPage>
(selected ? logic.session.active : null) ??
logic.session.preparedPlayerAt(index);
final videoPort = port is VideoPlayerPort ? port : null;
final ready = videoPort?.controller.value.isInitialized ?? false;
final handoff = selected ? logic.session.handoffAt(index) : null;
final handoffPort = handoff is VideoPlayerPort ? handoff : null;
// 测试播放器没有纹理。有播放器但不是视频控制器时视为已就绪,避免加载圈一直转。
final videoReady = videoPort?.controller.value.isInitialized ?? false;
final ready = videoReady || port != null;
final theater = logic.pip || logic.pipPreparing;
final locked = logic.session.isLocked || episode.locked;
if (selected && ready) {
if (selected && videoPort != null && videoPort.controller.value.isInitialized) {
unawaited(
_spriteAxisService.prepareAt(
episode.thumbnailsUrl,
videoPort!.controller.value.position,
videoPort.controller.value.position,
),
);
}
@@ -567,11 +571,30 @@ class _PlayerPageState extends State<PlayerPage>
),
PlayerVideoSurface(
controller: videoPort?.controller,
handoff: handoffPort?.controller,
videoUrl: videoPort?.controller.dataSource ?? episode.videoUrl,
theater: theater,
),
if (selected &&
!theater &&
!ready &&
!logic.ticketLoading &&
logic.ticketError == null &&
logic.session.error == null &&
logic.blockedEpisodeId != episode.id &&
!logic.session.isLocked)
const Center(
child: SizedBox.square(
dimension: _playerLoadingSize,
child: CircularProgressIndicator(
key: Key('player-video-loading'),
color: AppColors.blue,
strokeWidth: _playerLoadingStrokeWidth,
),
),
),
// 票据三态之一:起播前正在向后端要签名地址
if (selected && logic.ticketLoading)
if (selected && !theater && logic.ticketLoading)
const Center(
child: SizedBox.square(
dimension: _playerLoadingSize,
@@ -583,7 +606,10 @@ class _PlayerPageState extends State<PlayerPage>
),
),
// 票据三态之二:拿票失败(断网/服务异常)→ 可重试,不假装在加载
if (selected && !logic.ticketLoading && logic.ticketError != null)
if (selected &&
!theater &&
!logic.ticketLoading &&
logic.ticketError != null)
Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 36),
@@ -610,7 +636,7 @@ class _PlayerPageState extends State<PlayerPage>
),
),
),
if (selected && !ready && logic.session.error != null)
if (selected && !theater && !ready && logic.session.error != null)
Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 36),
@@ -634,6 +660,7 @@ class _PlayerPageState extends State<PlayerPage>
),
// 没有票据信息时的兜底(例如详情里就没地址、也没走票据流程)
if (selected &&
!theater &&
!ready &&
logic.blockedEpisodeId != episode.id &&
logic.session.error == null &&
@@ -668,7 +695,7 @@ class _PlayerPageState extends State<PlayerPage>
l10n: l10n,
drama: drama,
episode: episode,
controller: ready ? videoPort!.controller : null,
controller: videoReady ? videoPort!.controller : null,
locked: locked,
visible: _chromeVisible,
boosting: _boosting,
@@ -699,11 +726,11 @@ class _PlayerPageState extends State<PlayerPage>
},
onEpisodes: () => logic.showEpisodes(context),
onMore: _openCurrentMore,
onScrubStart: ready ? () => logic.beginScrub(videoPort!) : null,
onScrubStart: videoReady ? () => logic.beginScrub(videoPort!) : null,
onScrubEnd: _finishFeedScrub,
onScrubVisibilityChanged: _setScrubbing,
cancelScrubRequest: widget.scrubCancelRequest,
onSeek: ready
onSeek: videoReady
? (position) => logic.endScrub(context, videoPort!, position)
: null,
thumbnailService: _thumbnailService,
@@ -715,7 +742,7 @@ class _PlayerPageState extends State<PlayerPage>
l10n: l10n,
drama: drama,
episode: episode,
controller: ready ? videoPort!.controller : null,
controller: videoReady ? videoPort!.controller : null,
locked: locked,
liked: interactions.isEpisodeLiked(episode.id),
likeCount:
@@ -751,14 +778,14 @@ class _PlayerPageState extends State<PlayerPage>
onSave: () => unawaited(_toggleSave(context, drama)),
onShare: () => logic.shareDrama(context, drama),
onMore: () => _openMore(context, episode),
onScrubStart: ready
onScrubStart: videoReady
? () {
_setScrubbing(true);
logic.beginScrub(videoPort!);
}
: null,
onScrubEnd: () => _setScrubbing(false),
onSeek: ready
onSeek: videoReady
? (position) => logic.seekTo(context, videoPort!, position)
: null,
onLongPressCenter: () => _openMore(context, episode),
@@ -768,7 +795,10 @@ class _PlayerPageState extends State<PlayerPage>
controlsVisible: _chromeVisible,
),
// 票据三态之三:后端判定不可播放 —— 用 accessType 驱动文案,不在前端猜
if (selected && !ready && logic.blockedEpisodeId == episode.id)
if (selected &&
!theater &&
!ready &&
logic.blockedEpisodeId == episode.id)
PlayerBlockedNotice(
l10n: l10n,
episode: episode,
+15
View File
@@ -27,12 +27,14 @@ extension _PlayerViewActions on _PlayerPageState {
state: PlayerMoreState(
speed: _playbackSpeed,
qualities: logic.qualities,
selectedQuality: logic.selectedQuality,
),
actions: PlayerMoreActions(
onSpeedChanged: (value) {
_updatePlaybackSpeed(value);
unawaited(logic.setPlaybackSpeed(value));
},
onQualityChanged: (quality) => _switchQuality(context, l10n, quality),
onClear: _hideChrome,
onDownload: () => requestEpisodeDownload(context, episode.id),
onPip: logic.pictureInPicture.isPlatformSupported
@@ -43,6 +45,19 @@ extension _PlayerViewActions on _PlayerPageState {
);
}
Future<bool> _switchQuality(
BuildContext context,
AppLocalizations l10n,
String quality,
) async {
Navigator.of(context).pop();
final switched = await logic.selectQuality(quality);
if (!context.mounted || !switched) return false;
final label = quality.toUpperCase() == 'AUTO' ? l10n.qualityAuto : quality;
showCenteredToast(context, l10n.qualitySwitched(label));
return true;
}
Future<void> _openUnlockSheet(
BuildContext context,
int index,
@@ -401,11 +401,12 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
Widget build(BuildContext context) {
return Positioned.fill(
child: IgnorePointer(
child: SafeArea(
child: Align(
alignment: const Alignment(0, 0.55),
child: Semantics(
liveRegion: true,
child: Align(
alignment: const Alignment(0, -0.4),
child: Semantics(
liveRegion: true,
child: Material(
type: MaterialType.transparency,
child: Container(
key: const Key('comment-post-success-snackbar'),
padding: const EdgeInsets.symmetric(
@@ -422,6 +423,8 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
style: const TextStyle(
color: AppColors.onPrimary,
fontSize: 14,
decoration: TextDecoration.none,
decorationColor: AppColors.transparent,
),
),
),
+62 -29
View File
@@ -110,12 +110,16 @@ class HomeFeedOverlay extends StatefulWidget {
}
class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
static const Duration _singleTapDelay = Duration(milliseconds: 320);
static const Duration _singleTapDelay = Duration(milliseconds: 400);
bool _scrubbing = false;
bool _wasVisibleBeforeScrub = true;
Timer? _singleTapTimer;
DateTime? _lastTapAt;
DateTime? _lastDownAt;
DateTime? _blockSingleTapUntil;
bool _doubleTapDown = false;
bool _likedThisPair = false;
int _downSerial = 0;
int _tapSeq = 0;
int _nextHeartBurstId = 0;
final List<({int id, Offset position})> _heartBursts = [];
@@ -146,6 +150,7 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
builder: (context, constraints) => Listener(
onPointerUp: (_) => widget.onBoostEnd(),
onPointerCancel: (_) => widget.onBoostEnd(),
onPointerDown: _handlePointerDown,
child: GestureDetector(
key: const Key('home-feed-gesture'),
behavior: HitTestBehavior.opaque,
@@ -258,38 +263,66 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
widget.onScrubEnd?.call(wasVisible);
}
void _handleTapUp(TapUpDetails details) {
final tapSeq = ++_tapSeq;
final now = widget.now?.call() ?? DateTime.now();
final lastTap = _lastTapAt;
if (lastTap != null && now.difference(lastTap) <= _singleTapDelay) {
_tapSeq++;
_singleTapTimer?.cancel();
_singleTapTimer = null;
_lastTapAt = null;
_showHearts(details.localPosition);
DateTime _now() => widget.now?.call() ?? DateTime.now();
void _handlePointerDown(PointerDownEvent event) {
final now = _now();
final previous = _lastDownAt;
_downSerial++;
_lastDownAt = now;
final repeated =
previous != null && now.difference(previous) <= _singleTapDelay;
if (!repeated) {
if (_singleTapBlocked(now)) return;
_doubleTapDown = false;
_likedThisPair = false;
return;
}
_lastTapAt = now;
_doubleTapDown = true;
_blockSingleTapUntil = now.add(_singleTapDelay);
_cancelPendingSingleTap();
}
bool _singleTapBlocked(DateTime now) {
final blockedUntil = _blockSingleTapUntil;
return blockedUntil != null && now.isBefore(blockedUntil);
}
void _cancelPendingSingleTap() {
_tapSeq++;
_singleTapTimer?.cancel();
_singleTapTimer = null;
}
void _handleTapUp(TapUpDetails details) {
final now = _now();
if (_doubleTapDown || _singleTapBlocked(now)) {
_showDoubleTapLike(details.localPosition);
return;
}
final serial = _downSerial;
final tapSeq = ++_tapSeq;
_singleTapTimer?.cancel();
late final Timer pending;
pending = Timer(_singleTapDelay, () {
if (identical(_singleTapTimer, pending)) {
_singleTapTimer = null;
}
if (tapSeq != _tapSeq) return;
final latestTap = _lastTapAt;
if (latestTap != null &&
(widget.now?.call() ?? DateTime.now()).difference(latestTap) <
_singleTapDelay) {
return;
}
_lastTapAt = null;
if (mounted) widget.onTogglePlay();
if (!identical(_singleTapTimer, pending)) return;
_singleTapTimer = null;
if (!mounted || tapSeq != _tapSeq || serial != _downSerial) return;
if (_doubleTapDown || _singleTapBlocked(_now())) return;
_lastDownAt = null;
widget.onTogglePlay();
});
_singleTapTimer = pending;
}
void _showDoubleTapLike(Offset position) {
if (_likedThisPair) return;
_likedThisPair = true;
_blockSingleTapUntil = _now().add(_singleTapDelay);
_cancelPendingSingleTap();
_showHearts(position);
}
void _showHearts(Offset position) {
final id = _nextHeartBurstId++;
setState(() => _heartBursts.add((id: id, position: position)));
@@ -302,11 +335,11 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
}
void _handleLongPressStart(LongPressStartDetails details, double width) {
_tapSeq++;
_singleTapTimer?.cancel();
_singleTapTimer = null;
_lastTapAt = null;
final third = width / 3;
_tapSeq++;
_cancelPendingSingleTap();
_doubleTapDown = false;
_lastDownAt = null;
final dx = details.localPosition.dx;
if (dx < third || dx > width - third) {
widget.onBoostStart();
@@ -316,9 +316,13 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
final dragging = _preview != null;
final trackHeight = dragging ? _trackActiveHeight : widget.height;
final size = dragging ? _thumbActiveSize : _thumbSize;
final thumbSlotLeft = (width * fraction - _thumbActiveSize / 2)
.clamp(0.0, width - _thumbActiveSize)
.toDouble();
final finger = (width * fraction).clamp(0.0, width).toDouble();
final thumbSlotLeft = dragging
? finger - _thumbActiveSize / 2
: (finger - _thumbActiveSize / 2)
.clamp(0.0, width - _thumbActiveSize)
.toDouble();
final playedWidth = dragging ? finger : width * fraction;
final trackSlotBottom = _lineCenterFromBottom - _trackActiveHeight / 2;
final thumbSlotBottom = _lineCenterFromBottom - _thumbActiveSize / 2;
return SizedBox(
@@ -348,9 +352,10 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
Align(
alignment: Alignment.centerLeft,
child: AnimatedContainer(
duration: _trackResizeDuration,
key: const Key('home-feed-progress-played'),
duration: dragging ? Duration.zero : _trackResizeDuration,
curve: Curves.easeOut,
width: width * fraction,
width: playedWidth,
height: trackHeight,
color: AppColors.blue,
),
@@ -132,17 +132,19 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
),
),
const SizedBox(width: 8),
Text(
l10n.favoriteEpisodeProgress(
widget.episode.number,
widget.drama.episodeCount,
),
key: const Key('home-feed-episode-progress'),
maxLines: 1,
softWrap: false,
style: const TextStyle(
color: AppColors.overlayLabel,
fontSize: _tagFont,
Flexible(
child: Text(
l10n.favoriteEpisodeProgress(
widget.episode.number,
widget.drama.episodeCount,
),
key: const Key('home-feed-episode-progress'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.overlayLabel,
fontSize: _tagFont,
),
),
),
],
@@ -1,11 +1,39 @@
// Author: fruit.com.cn
import 'dart:math';
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
const int _heartDurationMs = 680;
const double _heartPopPortion = 0.18;
const double _heartStartScale = 0.7;
const double _heartHoldPortion = 0.45;
const List<_HeartParticle> _hearts = [
_HeartParticle(
delay: 0,
travel: 108,
drift: 0,
size: 48,
color: AppColors.doubleTapHeartRed,
),
_HeartParticle(
delay: 50,
travel: 96,
drift: -28,
size: 36,
color: AppColors.doubleTapHeartPink,
),
_HeartParticle(
delay: 90,
travel: 118,
drift: 26,
size: 40,
color: AppColors.doubleTapHeartRed,
),
];
/// 双击点赞时,在点击位置飘出一小簇心。
class PlayerDoubleTapHeartBurst extends StatefulWidget {
const PlayerDoubleTapHeartBurst({super.key, required this.onCompleted});
@@ -19,30 +47,14 @@ class PlayerDoubleTapHeartBurst extends StatefulWidget {
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final List<_HeartParticle> _particles;
bool _completed = false;
@override
void initState() {
super.initState();
final random = Random();
var delay = 0;
_particles = List.generate(3 + random.nextInt(2), (index) {
if (index > 0) delay += 40 + random.nextInt(21);
return _HeartParticle(
delay: delay,
duration: 600 + random.nextInt(101),
travel: 90 + random.nextInt(31),
drift: -18 + random.nextInt(37),
size: (20 + random.nextInt(7)).toDouble(),
color: random.nextBool()
? AppColors.doubleTapHeartRed
: AppColors.doubleTapHeartPink,
);
});
final total = _particles
.map((particle) => particle.delay + particle.duration)
.reduce(max);
final total = _hearts
.map((heart) => heart.delay + _heartDurationMs)
.reduce((left, right) => left > right ? left : right);
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: total),
@@ -76,7 +88,8 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
return Stack(
clipBehavior: Clip.none,
children: [
for (final particle in _particles) _particle(particle, elapsed),
for (var index = 0; index < _hearts.length; index++)
_heart(_hearts[index], elapsed, index),
],
);
},
@@ -85,27 +98,32 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
);
}
Widget _particle(_HeartParticle particle, double elapsed) {
final progress = ((elapsed - particle.delay) / particle.duration).clamp(
Widget _heart(_HeartParticle heart, double elapsed, int index) {
final progress = ((elapsed - heart.delay) / _heartDurationMs).clamp(
0.0,
1.0,
);
if (progress <= 0) return const SizedBox.shrink();
final move = Curves.easeOutCubic.transform(progress);
final scale = progress < 0.3
? 0.55 + (1.15 - 0.55) * (progress / 0.3)
: 1.15 - (1.15 - 0.2) * ((progress - 0.3) / 0.7);
final scale = progress < _heartPopPortion
? _heartStartScale +
(1 - _heartStartScale) * (progress / _heartPopPortion)
: 1.0;
final opacity = progress < _heartHoldPortion
? 1.0
: 1 - ((progress - _heartHoldPortion) / (1 - _heartHoldPortion));
return Positioned(
left: particle.drift * move - particle.size / 2,
top: -particle.travel * move,
left: heart.drift * move - heart.size / 2,
top: -heart.size / 2 - heart.travel * move,
child: Opacity(
opacity: 1 - Curves.easeIn.transform(progress),
opacity: opacity.clamp(0.0, 1.0),
child: Transform.scale(
scale: scale,
child: Icon(
key: Key('double-tap-heart-$index'),
Icons.favorite_rounded,
color: particle.color,
size: particle.size,
color: heart.color,
size: heart.size,
),
),
),
@@ -116,7 +134,6 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
class _HeartParticle {
const _HeartParticle({
required this.delay,
required this.duration,
required this.travel,
required this.drift,
required this.size,
@@ -124,9 +141,8 @@ class _HeartParticle {
});
final int delay;
final int duration;
final int travel;
final int drift;
final double travel;
final double drift;
final double size;
final Color color;
}
+34 -11
View File
@@ -22,19 +22,25 @@ const double _segmentTrackRadius = 10;
const double _segmentTrackPadding = 4;
const double _segmentPadding = 10;
const List<double> _speedOptions = [0.75, 1.0, 1.25, 1.5, 2.0, 3.0];
const List<String> _qualityOptions = ['AUTO', '720P', '1080P'];
const String _autoQuality = 'AUTO';
const List<String> _qualityOptions = ['AUTO', '360P', '480P', '720P', '1080P'];
/// 更多面板运行状态。
class PlayerMoreState {
/// 创建更多面板状态。
const PlayerMoreState({required this.speed, required this.qualities});
const PlayerMoreState({
required this.speed,
required this.qualities,
this.selectedQuality = 'AUTO',
});
/// 当前倍速。
final double speed;
/// 后端下发的清晰度档位。
final List<String> qualities;
/// 当前选中的档位,如 AUTO / 720P。
final String selectedQuality;
}
/// 更多面板动作集合。
@@ -44,6 +50,7 @@ class PlayerMoreActions {
required this.onSpeedChanged,
required this.onClear,
required this.onDownload,
required this.onQualityChanged,
this.onPip,
});
@@ -56,6 +63,9 @@ class PlayerMoreActions {
/// 离线缓存当前集。
final VoidCallback onDownload;
/// 切换清晰度。成功返回 true;失败时面板恢复到上一档。
final Future<bool> Function(String quality) onQualityChanged;
/// 进入小窗播放;平台不支持时为 null。
final VoidCallback? onPip;
}
@@ -85,6 +95,7 @@ class PlayerMoreSheet extends StatefulWidget {
class _PlayerMoreSheetState extends State<PlayerMoreSheet> {
late double _speed = widget.state.speed;
late String _quality = widget.state.selectedQuality.toUpperCase();
@override
Widget build(BuildContext context) {
@@ -247,19 +258,31 @@ class _PlayerMoreSheetState extends State<PlayerMoreSheet> {
);
}
Future<void> _chooseQuality(String quality) async {
if (_quality == quality) return;
final previous = _quality;
setState(() => _quality = quality);
final switched = await widget.actions.onQualityChanged(quality);
if (!mounted || switched) return;
setState(() => _quality = previous);
}
bool _hasQuality(String quality) {
final wanted = quality.toUpperCase();
for (final item in widget.state.qualities) {
if (item.toUpperCase() == wanted) return true;
}
return false;
}
Widget _qualitySegment(AppLocalizations l10n, String quality) {
final enabled = widget.state.qualities.contains(quality);
final selected =
quality == _autoQuality && enabled ||
!widget.state.qualities.contains(_autoQuality) &&
widget.state.qualities.isNotEmpty &&
widget.state.qualities.first == quality;
final enabled = _hasQuality(quality);
return _SegmentButton(
key: Key('player-more-quality-$quality'),
label: enabled ? quality : '$quality · ${l10n.qualityUnavailable}',
selected: selected,
selected: enabled && _quality == quality,
enabled: enabled,
onTap: enabled ? () {} : null,
onTap: enabled ? () => _chooseQuality(quality) : null,
);
}
+6 -5
View File
@@ -220,11 +220,12 @@ class PlayerPlaybackOverlay extends StatelessWidget {
),
if (data.boosting) _boostHint(),
_bottomProgress(),
// 加速或拖动进度时只留进度条,避免挡住画面。
Offstage(
offstage: data.boosting || scrubbing,
child: _bottomActions(),
),
// 加速时收起底栏。拖动进度时底栏只隐藏,占位保留,进度条不挪位。
scrubbing
? IgnorePointer(
child: Opacity(opacity: 0, child: _bottomActions()),
)
: Offstage(offstage: data.boosting, child: _bottomActions()),
],
),
);
@@ -1,7 +1,6 @@
// Author: fruit.com.cn
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:video_player/video_player.dart';
import '../../../core/data/models/drama.dart';
@@ -10,16 +10,18 @@ const Duration _videoFadeDuration = Duration(milliseconds: 200);
const double _errorHorizontal = 32;
const int _errorMaxLines = 3;
/// 黑色底层与视频层共用同一控制器,视频首帧就绪后再淡入。
/// 黑色底层与视频层共用同一控制器。清晰度切换时用仍在播放的旧画面盖住新纹理的黑帧。
class PlayerVideoSurface extends StatefulWidget {
const PlayerVideoSurface({
super.key,
required this.controller,
required this.videoUrl,
required this.theater,
this.handoff,
});
final VideoPlayerController? controller;
final VideoPlayerController? handoff;
final String videoUrl;
final bool theater;
@@ -48,7 +50,8 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
Widget _frame(VideoPlayerValue? value) {
final controller = widget.controller;
final reveal = _shouldReveal(value);
final handoff = _liveHandoff(controller);
final reveal = _shouldReveal(value, handoff != null);
_logStateChange(value);
return Stack(
fit: StackFit.expand,
@@ -60,7 +63,7 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
AnimatedOpacity(
key: const Key('player-video-opacity'),
opacity: reveal ? 1 : 0,
duration: _videoFadeDuration,
duration: handoff != null ? Duration.zero : _videoFadeDuration,
curve: Curves.easeOut,
child: reveal && controller != null
? _VideoLayer(
@@ -70,6 +73,13 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
)
: const SizedBox.expand(),
),
if (handoff != null)
_VideoLayer(
key: const Key('player-video-handoff'),
controller: handoff,
value: handoff.value,
theater: widget.theater,
),
if (kDebugMode && value?.hasError == true)
Center(
child: Padding(
@@ -88,12 +98,18 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
);
}
bool _shouldReveal(VideoPlayerValue? value) {
return value != null &&
!value.hasError &&
value.isInitialized &&
value.size.width > 0 &&
(value.position > Duration.zero || value.isPlaying);
bool _shouldReveal(VideoPlayerValue? value, bool covered) {
if (value == null || value.hasError || !value.isInitialized) return false;
if (value.size.width <= 0) return false;
if (covered) return true;
return value.position > Duration.zero || value.isPlaying;
}
/// 只画会话仍持有的旧画面,控制器一旦被换掉就不再引用。
VideoPlayerController? _liveHandoff(VideoPlayerController? controller) {
final handoff = widget.handoff;
if (handoff == null || identical(handoff, controller)) return null;
return handoff;
}
void _logStateChange(VideoPlayerValue? value) {
@@ -135,6 +151,7 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
class _VideoLayer extends StatelessWidget {
const _VideoLayer({
super.key,
required this.controller,
required this.value,
required this.theater,
@@ -13,6 +13,8 @@ import 'loading_progress_track.dart';
import 'scrub_preview_card.dart';
const Key _inactiveTrackKey = Key('progress-inactive');
const double _compactTrackSlot = 20;
const double _trackSlot = 44;
/// Keeps seeks within the playable range so dragging to the edge does not
/// trigger the player's completion callback before playback resumes.
@@ -241,11 +243,7 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
widget.thumbnailService != null &&
(widget.episodeId?.isNotEmpty ?? false);
final trackHeight = scrubbing ? 6.0 : 2.0;
final trackAreaHeight = loading
? (widget.compact ? 20.0 : 44.0)
: widget.compact
? (scrubbing ? 32.0 : 20.0)
: (scrubbing ? 48.0 : 44.0);
final trackAreaHeight = widget.compact ? _compactTrackSlot : _trackSlot;
return LayoutBuilder(
builder: (context, constraints) {
+36 -27
View File
@@ -25,12 +25,18 @@ class RecommendPage extends StatefulWidget {
required this.feedController,
required this.active,
required this.onSearch,
this.videoOnly = false,
this.onImmersiveChanged,
});
final HomeFeedController feedController;
final bool active;
final VoidCallback onSearch;
/// 画中画时只留视频,不画顶栏。
final bool videoOnly;
final ValueChanged<bool>? onImmersiveChanged;
@override
State<RecommendPage> createState() => _RecommendPageState();
}
@@ -84,40 +90,42 @@ class _RecommendPageState extends State<RecommendPage> {
),
),
),
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: SizedBox(
height: 72,
child: DecoratedBox(
key: const Key('recommend-top-gradient'),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [AppColors.mediaBlack, AppColors.transparent],
if (!widget.videoOnly)
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: SizedBox(
height: 72,
child: DecoratedBox(
key: const Key('recommend-top-gradient'),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [AppColors.mediaBlack, AppColors.transparent],
),
),
),
),
),
),
),
Positioned(
top: 0,
left: 0,
right: 0,
child: SafeArea(
bottom: false,
child: RecommendTopNav(
selected: _tab,
onVideo: _tab == RecommendInnerTab.feed,
onSelected: _selectTab,
onSearch: _handleSearch,
if (!widget.videoOnly)
Positioned(
top: 0,
left: 0,
right: 0,
child: SafeArea(
bottom: false,
child: RecommendTopNav(
selected: _tab,
onVideo: _tab == RecommendInnerTab.feed,
onSelected: _selectTab,
onSearch: _handleSearch,
),
),
),
),
],
),
);
@@ -155,6 +163,7 @@ class _RecommendPageState extends State<RecommendPage> {
_openDrama(drama, episodeId: episode.id),
onRefreshFeed: widget.feedController.refreshCurrent,
onLoadMore: widget.feedController.loadMore,
onImmersiveChanged: widget.onImmersiveChanged,
scrubCancelRequest: _scrubCancelRequest,
);
}
@@ -75,13 +75,7 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
child: EmptyState(
key: const Key('all-dramas-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.homeGridFilterEmpty,
actionLabel: l10n.homeGridClearFilter,
onAction: () => setState(() {
_region = 'all';
_audio = 'all';
_genre = null;
}),
title: l10n.emptyContent,
),
)
else
@@ -12,6 +12,7 @@ const double _tabGap = 22;
const double _tabFont = 17;
const double _searchHitSize = 40;
const double _searchIconSize = 26;
const double _minNavWidth = 280;
class RecommendTopNav extends StatelessWidget {
const RecommendTopNav({
@@ -40,6 +41,22 @@ class RecommendTopNav extends StatelessWidget {
final shadows = onVideo
? const [Shadow(color: AppColors.mediaBlack, blurRadius: 6)]
: null;
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < _minNavWidth) {
return const SizedBox(key: Key('recommend-top-nav'), height: height);
}
return _bar(context, items, shadows);
},
);
}
Widget _bar(
BuildContext context,
List<(RecommendInnerTab, String, String)> items,
List<Shadow>? shadows,
) {
final l10n = AppLocalizations.of(context)!;
return SizedBox(
key: const Key('recommend-top-nav'),
height: height,
@@ -50,20 +67,23 @@ class RecommendTopNav extends StatelessWidget {
child: Stack(
alignment: Alignment.center,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
for (var index = 0; index < items.length; index++) ...[
if (index > 0) const SizedBox(width: _tabGap),
_tab(
key: Key('recommend-tab-${items[index].$3}'),
label: items[index].$2,
selected: selected == items[index].$1,
shadows: shadows,
onTap: () => onSelected(items[index].$1),
),
FittedBox(
fit: BoxFit.scaleDown,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (var index = 0; index < items.length; index++) ...[
if (index > 0) const SizedBox(width: _tabGap),
_tab(
key: Key('recommend-tab-${items[index].$3}'),
label: items[index].$2,
selected: selected == items[index].$1,
shadows: shadows,
onTap: () => onSelected(items[index].$1),
),
],
],
],
),
),
Align(
alignment: Alignment.centerRight,
+104
View File
@@ -0,0 +1,104 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/legal/legal_opener.dart';
import '../../core/legal/legal_page.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_dimens.dart';
import '../../l10n/app_localizations.dart';
/// 设置页里的服务条款和隐私协议。点一行就打开当前语言的公开页。
class LegalLinksCard extends StatelessWidget {
const LegalLinksCard({super.key, this.open});
final Future<void> Function(String url)? open;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final rows = <_LegalRow>[
_LegalRow(
key: const Key('settings-terms'),
title: l10n.legalTerms,
path: legalTermsPath,
),
_LegalRow(
key: const Key('settings-privacy'),
title: l10n.legalPrivacy,
path: legalPrivacyPath,
),
];
return Material(
color: AppColors.card,
borderRadius: BorderRadius.circular(AppDimens.cardRadius),
clipBehavior: Clip.antiAlias,
child: Column(
children: [
for (var index = 0; index < rows.length; index++) ...[
if (index > 0)
const Divider(
height: AppDimens.mineGridDividerWidth,
thickness: AppDimens.mineGridDividerWidth,
color: AppColors.outlineVariantDark,
),
_tile(context, rows[index]),
],
],
),
);
}
Widget _tile(BuildContext context, _LegalRow row) {
return InkWell(
key: row.key,
onTap: () => _open(context, row.path),
child: SizedBox(
height: AppDimens.mineMoreRowHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppDimens.spaceLg),
child: Row(
children: [
Expanded(
child: Text(
row.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: AppDimens.listTitle,
),
),
),
const Icon(
Icons.chevron_right_rounded,
color: AppColors.textSecondary,
size: AppDimens.accountIcon,
),
],
),
),
),
);
}
void _open(BuildContext context, String path) {
final url = legalPageUrl(path, Localizations.localeOf(context));
final custom = open;
if (custom != null) {
unawaited(custom(url));
return;
}
unawaited(openLegalUrlOrNotify(context, url));
}
}
class _LegalRow {
const _LegalRow({required this.key, required this.title, required this.path});
final Key key;
final String title;
final String path;
}
+5 -29
View File
@@ -6,16 +6,15 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_dimens.dart';
import '../../core/theme/app_theme.dart';
import '../../core/widgets/auth_gate.dart';
import '../../core/widgets/plain_page_scaffold.dart';
import '../../l10n/app_localizations.dart';
import '../account/account_entry_card.dart';
import '../notices/notices_page.dart';
import 'legal_links_card.dart';
/// 设置页:收纳账号、通知与登录态,不提供手动语言切换。
/// 设置页:账号入口按列表展示,不提供通知和手动语言切换。
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@@ -34,10 +33,10 @@ class SettingsPage extends StatelessWidget {
children: [
if (auth.isSignedIn) ...[
const AccountEntryCard(),
const SizedBox(height: 12),
const SizedBox(height: AppDimens.spaceXl),
],
_noticesTile(context, l10n),
const SizedBox(height: 24),
const LegalLinksCard(),
const SizedBox(height: AppDimens.spaceXl),
_authAction(context, l10n, auth),
],
),
@@ -45,29 +44,6 @@ class SettingsPage extends StatelessWidget {
);
}
Widget _noticesTile(BuildContext context, AppLocalizations l10n) {
return Material(
color: AppColors.card,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppDimens.cardRadius),
side: const BorderSide(color: AppColors.border),
),
clipBehavior: Clip.antiAlias,
child: ListTile(
key: const Key('settings-notices'),
leading: const Icon(
Icons.notifications_none_rounded,
color: AppColors.blueSoft,
),
title: Text(l10n.notices),
trailing: const Icon(Icons.chevron_right_rounded),
onTap: () => Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => const NoticesPage())),
),
);
}
Widget _authAction(
BuildContext context,
AppLocalizations l10n,