Author SHA1 Message Date
Vicky c027acc91f feat(recommend): 新增推荐频道页并恢复首页沉浸式信息流
- tab1 推荐页改为接口分类频道:频道导航可横滑,选中频道自动滚动到可视区,内容区左右滑动切换分类
- 精选频道:顶部固定高度 banner 轮播图 + 接口 tag 筛选的上新短剧横滑 + 其余短剧双列网格;其他分类三列网格
- 分类内容支持懒加载、下拉刷新与上拉分页加载
- 卡片角标文案与背景色取自接口 tag/tagColor,短剧标题统一白色
- 恢复 tab0 为沉浸式全屏视频首页及其三 inner-tab 顶导(搜索/礼物入口)
- l10n 新增原创出品、立即观看、上新、编辑精选、全N集等多语言文案
2026-10-27 19:57:42 +08:00
Vicky a3f3481f4f feat: phase1 UI prep — 设备ID系统传递 + 国家本地化展示 + 继续观看直进播放页
设备标识: Android SSAID/ iOS IDFV 原生通道 → Dart DeviceIdProvider
国家解析: 注册/登录从后端 IP → 国家/语言/时区/币种 自动落库
账号资料: 全部本地化展示 (account_display.dart)
我的页: 继续观看卡片点击直接进播放页
2026-10-27 15:45:20 +08:00
Vicky 1b19513efb feat(core): 设备号改用系统标识,重装不再变成新游客
- Android 读 SSAID、iOS 读 IDFV,均免权限,由原生通道提供,不引插件
- 取不到时回退本地 UUIDv4,替代原来 32 位随机 + 时间戳的拼接
2026-10-27 14:15:50 +08:00
Vicky 935de13343 refactor(core): 平台上报收敛为单个请求头
去掉 device_info_plus 依赖与机型/系统版本,只保留 X-Client-Platform。
2026-10-27 14:00:19 +08:00
Vicky 01a3b0101e chore(merge): 合并客户端设备画像上报 2026-10-27 13:54:29 +08:00
Vicky d6df5fbe5f feat(core): 请求头统一上报设备系统与机型
- 新增 DeviceProfileReader,首次读取后缓存,插件不可用时安全降级
- 拦截器为所有请求补 X-Client-Platform / Os / Model,匿名请求同样携带
2026-10-27 13:54:28 +08:00
Vicky 929b7f72f8 chore(merge): 合并右侧操作栏顺序统一 2026-10-27 13:35:41 +08:00
Vicky e028ca40b1 fix(ui): 统一播放页右侧操作栏顺序为收藏-点赞-评论-分享
与推荐页操作栏保持一致,同步更新布局断言。
2026-10-27 13:35:41 +08:00
Zhou Weidong d206465ee1 fix(recommend): 首屏不再兜出重试空态 2026-10-27 11:24:21 +08:00
Zhou Weidong 9117bf58b8 fix(ui): 拆分媒体骨架底色,恢复可见度 2026-10-27 11:16:24 +08:00
Zhou Weidong bd826a9236 fix(ui): 骨架屏扫光收窄压淡 2026-10-27 11:12:31 +08:00
Zhou Weidong a5dbae7fff fix(ui): 骨架屏改为逐卡片扫光 2026-10-27 11:08:43 +08:00
Zhou Weidong 00405d2e3b fix(ui): 收敛骨架屏亮度 2026-10-27 10:49:30 +08:00
Zhou Weidong 72dcb92aca fix(following): 收紧取消追剧确认弹窗 2026-10-27 10:34:07 +08:00
Zhou Weidong 8d511933df fix(mine): 支持未登录展示互动计数 2026-10-27 10:26:11 +08:00
Zhou Weidong 06a2f6d7c0 fix(following): 支持未登录追剧与历史 2026-10-27 10:13:27 +08:00
Zhou Weidong 0d785bf1f8 feat(library): 支持设备追剧与观看历史 2026-10-27 09:54:51 +08:00
Zhou Weidong 4c3acb047c fix(player): 收紧推荐页互动栏间距 2026-10-27 09:37:00 +08:00
Zhou Weidong d3dbc9f8dc fix(favorite): 统一收藏状态与互动图标 2026-10-27 09:31:48 +08:00
Zhou Weidong 4b97f89c0b fix(recommend): 延后推荐数据刷新 2026-10-27 09:19:18 +08:00
Zhou Weidong 6be024f86f test(flutter): 收敛异步配置与分页测试 2026-10-26 22:49:27 +08:00
Zhou Weidong 6512808506 test(ui): 更新主题导航与布局断言 2026-10-26 22:49:23 +08:00
Zhou Weidong 2d65cd3006 test(auth): 更新登录失败提示断言 2026-10-26 22:49:21 +08:00
Zhou Weidong 391b01e9d0 fix(theater): 修复新剧卡片与榜单溢出 2026-10-26 22:49:13 +08:00
Zhou Weidong d4ce3a5d8b fix(home): 修复目录错误态被占位层遮挡 2026-10-26 22:49:10 +08:00
Zhou Weidong bf47c065c9 fix(ui): 修复继续观看卡片纵向溢出 2026-10-26 22:49:07 +08:00
Zhou Weidong c6b3ca9311 fix(auth): 禁止刷新接口递归重试 2026-10-26 22:49:04 +08:00
Zhou Weidong a3d50eb935 feat(interaction): 支持游客点赞收藏评论 2026-10-26 22:33:14 +08:00
Zhou Weidong 188811fde6 feat(player): 切集刷新互动计数统计 2026-10-26 21:40:39 +08:00
Zhou Weidong 37353dac15 fix(player): 观看全集进入后自动播放 2026-10-26 21:25:38 +08:00
Zhou Weidong 350d16db75 fix(player): 修正缓冲态与首帧时间闪现 2026-10-26 21:13:55 +08:00
Zhou Weidong 0f27daf664 chore(merge): 合并播放器切集与双击点赞优化 2026-10-26 19:24:49 +08:00
Zhou Weidong afdc4af2f2 chore(player): 移除飘心毫秒调试文字 2026-10-26 19:21:24 +08:00
Zhou Weidong 1b50a73bfc fix(player): 修复首次双击点赞状态刷新 2026-10-26 19:17:14 +08:00
Zhou Weidong 978c309cd7 fix(player): 改用墙钟驱动飘心动画 2026-10-26 19:07:56 +08:00
Zhou Weidong c0f65042e6 fix(player): 修正飘心Overlay生命周期 2026-10-26 19:00:37 +08:00
Zhou Weidong a7d01e0306 test(player): 增加飘心像素定位回归 2026-10-26 18:57:04 +08:00
Zhou Weidong ed2cf4c18c fix(player): 使用根Overlay承载飘心 2026-10-26 18:54:05 +08:00
Zhou Weidong db3e153409 fix(player): 使用根Overlay承载飘心 2026-10-26 18:49:36 +08:00
Zhou Weidong 810ca5bf9d fix(player): 延长飘心并显示毫秒计时 2026-10-26 18:48:12 +08:00
Zhou Weidong 84b24775d6 fix(player): 恢复develop飘心实现 2026-10-26 18:38:59 +08:00
Zhou Weidong 9039b27c7f fix(player): 使用根Overlay渲染飘心 2026-10-26 18:35:30 +08:00
Zhou Weidong 30b43878ab fix(player): 使用根Overlay渲染飘心 2026-10-26 18:29:48 +08:00
Zhou Weidong e7afd316f8 fix(player): 放慢随机飘心并验证完整时长 2026-10-26 18:24:19 +08:00
Zhou Weidong f3dd4a9b5c fix(player): 恢复随机飘心粒子模型 2026-10-26 18:19:39 +08:00
Zhou Weidong 94b37ef00f fix(player): 优化双击飘心轨迹 2026-10-26 18:16:06 +08:00
Zhou Weidong bea50ab32f fix(player): 调整双击飘心动画 2026-10-26 18:11:01 +08:00
Zhou Weidong 63296d2a92 fix(player): 恢复独立播放页双击点赞 2026-10-26 18:06:55 +08:00
Zhou Weidong b291044acc fix(player): 收敛播放页入口加载态 2026-10-26 17:56:40 +08:00
Zhou Weidong ee4e573f4f fix(player): 播放页改为非阻塞加载 2026-10-26 17:43:57 +08:00
Zhou Weidong e8f192ccf8 fix(player): 顶层抓帧淡出揭幕 2026-10-26 17:31:59 +08:00
Zhou Weidong c8ec481fc9 fix(player): 预解码观看全集首帧 2026-10-26 17:27:43 +08:00
Zhou Weidong 1fc8c4924e fix(player): 调整观看全集淡入时长 2026-10-26 17:21:52 +08:00
Zhou Weidong 55fc2796a9 fix(player): 观看全集复用抓帧首屏 2026-10-26 17:20:24 +08:00
Zhou Weidong 4d3d067f77 fix(player): 规范预热回收日志并抓帧过渡 2026-10-26 17:13:56 +08:00
Zhou Weidong bb2c729a7e fix(player): 隔离播放资源所有权并修复黑屏 2026-10-26 17:03:19 +08:00
Zhou Weidong 54eb5a60a8 fix(player): 修复返回首页黑屏并恢复预热 2026-10-26 16:45:00 +08:00
Zhou Weidong 6667330ce0 fix(player): 分离首页与播放页播放上下文 2026-10-26 16:37:37 +08:00
Zhou Weidong 440188f261 fix(player): 修复切集返回推荐页黑屏 2026-10-26 16:20:31 +08:00
Zhou Weidong 9d2d3b97a1 fix(player): 独立全屏路由复用播放会话 2026-10-26 16:08:15 +08:00
Zhou Weidong 23e80dd637 fix(player): 复用播放会话进入全屏 2026-10-26 15:55:46 +08:00
Zhou Weidong ab4c246675 fix(player): 保持推荐页返回时播放状态 2026-10-26 15:44:28 +08:00
Zhou Weidong 2a32dec183 fix(player): 持久化竖滑播放画面层 2026-10-26 15:34:24 +08:00
Zhou Weidong 5dafc68775 test(player): 覆盖 feed 高清首帧解析 2026-10-26 15:20:45 +08:00
Zhou Weidong 80c962a95c fix(player): 收紧图片与快速切集资源占用 2026-10-26 15:10:02 +08:00
Zhou Weidong 2fef7470e0 fix(player): 使用高清首帧并稳定切集占位 2026-10-26 14:58:00 +08:00
Zhou Weidong 0cb0ab0613 fix(player): 重构单层过渡并阻止锁定集串播 2026-10-26 14:41:18 +08:00
Zhou Weidong 70d8e0f982 fix(player): 使用雪碧图预热首帧兜底 2026-10-26 14:21:52 +08:00
Zhou Weidong 48b4e67d34 fix(player): 预热直出并与视频统一封面布局 2026-10-26 14:12:42 +08:00
Zhou Weidong a3a79f7068 fix(player): 修正封面比例与首帧切换闪烁 2026-10-26 14:07:36 +08:00
Zhou Weidong 04f034817c fix(player): 优化封面过渡与换集起播 2026-10-26 14:01:42 +08:00
Zhou Weidong 516593499c fix(player): 修复竖滑上一集不自动播放 2026-10-26 13:43:43 +08:00
Zhou Weidong df36890b48 chore(analyze): 清理静态检查告警 2026-10-26 13:43:38 +08:00
142 changed files with 10610 additions and 1790 deletions

No files matched your search

@@ -4,6 +4,7 @@ package com.stormg.lumadrama
import android.content.Intent
import android.app.PictureInPictureParams
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
@@ -12,6 +13,8 @@ import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.telephony.TelephonyManager
import android.util.Rational
import android.content.pm.PackageManager
import android.view.WindowManager
@@ -21,6 +24,7 @@ import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.ByteArrayOutputStream
import java.util.Locale
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
@@ -65,6 +69,23 @@ class MainActivity : FlutterActivity() {
result.success(false)
}
}
// 设备标识:SSAID 免权限,卸载重装不变,避免客户端自己生成的 id 每次重装都变
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.stormg.lumadrama/device")
.setMethodCallHandler { call, result ->
when (call.method) {
"ssaid" -> {
val value = try {
Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
} catch (_: Exception) {
null
}
result.success(value)
}
// 设备区域:注册时作为服务端 IP 解析失败后的兜底
"region" -> result.success(currentRegion())
else -> result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.stormg.lumadrama/share")
.setMethodCallHandler { call, result ->
if (call.method != "shareText") {
@@ -156,6 +177,28 @@ class MainActivity : FlutterActivity() {
?.bottom
?: 0
/** 网络运营商国家优先,其次 SIM 卡,最后系统语言;都拿不到返回空串。 */
private fun currentRegion(): String {
return try {
val telephony = getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
val localeCountry = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
resources.configuration.locales.get(0).country
} else {
@Suppress("DEPRECATION")
resources.configuration.locale.country
}
val candidates = listOfNotNull(
telephony?.networkCountryIso,
telephony?.simCountryIso,
localeCountry
)
candidates.firstOrNull { it.isNotBlank() }?.uppercase(Locale.ROOT) ?: ""
} catch (_: Exception) {
// 个别 ROM 读运营商信息会抛 SecurityException,别让注册流程卡住
""
}
}
private fun emitImeInset(value: Int) {
if (value == imeInset) return
imeInset = value
+24
View File
@@ -63,6 +63,7 @@ final class RunnerFlutterViewController: FlutterViewController {
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
registerWirelessDataChannel(engineBridge)
registerDeviceIdChannel(engineBridge)
let channel = FlutterMethodChannel(
name: "com.stormg.lumadrama/share",
binaryMessenger: engineBridge.applicationRegistrar.messenger()
@@ -144,6 +145,29 @@ final class RunnerFlutterViewController: FlutterViewController {
}
}
/// 设备标识:IDFV 免权限,卸载本 App 不变,避免客户端自生成的 id 每次重装都变。
/// 同通道顺带提供设备区域(ISO-2),注册时作为服务端 IP 解析失败后的兜底。
private func registerDeviceIdChannel(_ engineBridge: FlutterImplicitEngineBridge) {
let channel = FlutterMethodChannel(
name: "com.stormg.lumadrama/device",
binaryMessenger: engineBridge.applicationRegistrar.messenger()
)
channel.setMethodCallHandler { call, result in
switch call.method {
case "idfv":
result(UIDevice.current.identifierForVendor?.uuidString)
case "region":
if #available(iOS 16.0, *) {
result(Locale.current.region?.identifier)
} else {
result(Locale.current.regionCode)
}
default:
result(FlutterMethodNotImplemented)
}
}
}
private func registerWirelessDataChannel(_ engineBridge: FlutterImplicitEngineBridge) {
let channel = FlutterMethodChannel(
name: WirelessDataPrompt.channelName,
+1 -1
View File
@@ -48,7 +48,7 @@
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>10.43.47.1</key>
<key>192.168.31.243</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
+8 -13
View File
@@ -14,6 +14,7 @@ import 'core/data/remote/catalog_api.dart';
import 'core/data/remote/category_api.dart';
import 'core/data/remote/comment_api.dart';
import 'core/data/remote/commerce_api.dart';
import 'core/data/remote/device_profile.dart';
import 'core/data/remote/download_api.dart';
import 'core/data/remote/interaction_api.dart';
import 'core/data/remote/library_api.dart';
@@ -117,12 +118,13 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
late final AuthSessionStore _sessionStore = AuthSessionStore();
/// 全 App 共用一个 ApiClient:这样目录、账号、后续的互动/进度请求
/// 都自动带 `Authorization` 与 `X-Device-Id`,401 的刷新重试也只有一处实现。
/// 都自动带 `Authorization`、`X-Device-Id` 与平台头,401 的刷新重试也只有一处实现。
late final ApiClient _apiClient = ApiClient(
accessTokenReader: () => _auth.accessToken,
tokenRefresher: () => _auth.refresh(),
onUnauthorized: () => _auth.clear(),
deviceIdReader: _sessionStore.deviceId,
platformReader: clientPlatform,
);
late final AuthController _auth = AuthController(
@@ -141,17 +143,11 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
late final WatchHistoryRepository _watchHistory =
widget.watchHistoryRepository ??
HttpWatchHistoryRepository(
WatchApi(_apiClient),
isSignedIn: () => _auth.isSignedIn,
);
HttpWatchHistoryRepository(WatchApi(_apiClient));
late final FavoriteRepository _favorites =
widget.favoriteRepository ??
HttpFavoriteRepository(
LibraryApi(_apiClient),
isSignedIn: () => _auth.isSignedIn,
);
HttpFavoriteRepository(LibraryApi(_apiClient));
late final PlaybackRepository _playback =
widget.playbackRepository ??
@@ -219,7 +215,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
unawaited(_localeController.load());
// 登录/登出时同步收藏状态:收藏属于账号,不能跨账号串联
_auth.addListener(_onAuthChanged);
if (_auth.isSignedIn) unawaited(_favoriteController.load());
unawaited(_favoriteController.load());
if (_auth.isSignedIn) unawaited(_walletController.load());
unawaited(_downloadController.restore());
}
@@ -235,6 +231,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
unawaited(_walletController.load());
} else {
_favoriteController.clear();
unawaited(_favoriteController.load());
_downloadController.reset();
_walletController.reset();
}
@@ -293,9 +290,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
),
ChangeNotifierProvider(create: (_) => _createCategories()),
if (playlists != null)
ChangeNotifierProvider(
create: (_) => PlaylistController(playlists),
),
ChangeNotifierProvider(create: (_) => PlaylistController(playlists)),
ChangeNotifierProvider.value(value: _favoriteController),
ChangeNotifierProvider.value(value: _downloadController),
ChangeNotifierProvider.value(value: _walletController),
+1 -1
View File
@@ -14,7 +14,7 @@ class AppConfig {
/// 开发调试默认服务地址,当前指向本机局域网 IP。
///
/// 换网络时只改这一行,地址不要带结尾斜杠。
static const String devHostBaseUrl = 'http://10.43.47.1:8081';
static const String devHostBaseUrl = 'http://192.168.31.243:8081';
/// 本机后端地址:通过 `adb reverse tcp:8081 tcp:8081` 映射到开发机,
/// 探测可达时 App 直连本机服务;不可达时回落到公网地址。
+20 -1
View File
@@ -21,6 +21,7 @@ class Episode {
this.likeCount,
this.commentCount,
this.thumbnailsUrl,
this.posterUrl,
});
final String id;
@@ -37,12 +38,14 @@ class Episode {
final int? likeCount;
final int? commentCount;
final String? thumbnailsUrl;
final String? posterUrl;
Episode withVideoUrl(
String url, {
int? likeCount,
int? commentCount,
String? thumbnailsUrl,
String? posterUrl,
}) => Episode(
id: id,
number: number,
@@ -54,6 +57,21 @@ class Episode {
likeCount: likeCount ?? this.likeCount,
commentCount: commentCount ?? this.commentCount,
thumbnailsUrl: thumbnailsUrl ?? this.thumbnailsUrl,
posterUrl: posterUrl ?? this.posterUrl,
);
Episode withStats({int? likeCount, int? commentCount}) => Episode(
id: id,
number: number,
title: title,
isFree: isFree,
videoUrl: videoUrl,
durationSec: durationSec,
locked: locked,
likeCount: likeCount ?? this.likeCount,
commentCount: commentCount ?? this.commentCount,
thumbnailsUrl: thumbnailsUrl,
posterUrl: posterUrl,
);
factory Episode.fromJson(Map<String, dynamic> json) {
@@ -68,6 +86,7 @@ class Episode {
likeCount: _optionalInt(json['likeCount']),
commentCount: _optionalInt(json['commentCount']),
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
posterUrl: _optionalString(json['posterUrl']),
);
}
}
@@ -324,4 +343,4 @@ String _genreText(List<Map<String, String>> types, Object? fallback) {
final joined = names.join(' / ');
if (joined.isNotEmpty) return joined;
return fallback is String ? fallback : '';
}
}
+55
View File
@@ -0,0 +1,55 @@
// Author: fruit.com.cn
import 'json_numbers.dart';
/// 播放页轻量互动计数快照,不包含播放地址或票据信息。
class EpisodeStats {
const EpisodeStats({
required this.episodeId,
required this.dramaId,
required this.likeCount,
required this.commentCount,
required this.favoriteCount,
required this.liked,
required this.favorited,
});
final String episodeId;
final String dramaId;
final int likeCount;
final int commentCount;
final int favoriteCount;
final bool liked;
final bool favorited;
EpisodeStats copyWith({
String? dramaId,
int? likeCount,
int? commentCount,
int? favoriteCount,
bool? liked,
bool? favorited,
}) {
return EpisodeStats(
episodeId: episodeId,
dramaId: dramaId ?? this.dramaId,
likeCount: likeCount ?? this.likeCount,
commentCount: commentCount ?? this.commentCount,
favoriteCount: favoriteCount ?? this.favoriteCount,
liked: liked ?? this.liked,
favorited: favorited ?? this.favorited,
);
}
factory EpisodeStats.fromJson(Map<String, dynamic> json) {
return EpisodeStats(
episodeId: jsonToId(json['episodeId']),
dramaId: jsonToId(json['dramaId']),
likeCount: jsonToInt(json['likeCount']),
commentCount: jsonToInt(json['commentCount']),
favoriteCount: jsonToInt(json['favoriteCount']),
liked: json['liked'] == true,
favorited: json['favorited'] == true,
);
}
}
+5 -3
View File
@@ -58,14 +58,16 @@ class LikeToggleResult {
/// 控制器统一返回结果;失败消息可直接展示后端 `message`。
class OperationResult<T> {
const OperationResult._(this.data, this.errorMessage);
const OperationResult._(this.data, this.errorMessage, this.errorCode);
const OperationResult.success([T? data]) : this._(data, null);
const OperationResult.success([T? data]) : this._(data, null, null);
const OperationResult.failure(this.errorMessage) : data = null;
const OperationResult.failure(this.errorMessage, {this.errorCode})
: data = null;
final T? data;
final String? errorMessage;
final int? errorCode;
bool get isSuccess => errorMessage == null;
}
+3
View File
@@ -16,6 +16,7 @@ class PlayTicket {
this.qualities = const [],
this.tracks = const [],
this.thumbnailsUrl,
this.posterUrl,
this.likeCount,
this.commentCount,
});
@@ -46,6 +47,7 @@ class PlayTicket {
/// 各档签名地址。AUTO 是主列表,点选其它档位时换成对应地址。
final List<PlayQualityTrack> tracks;
final String? thumbnailsUrl;
final String? posterUrl;
final int? likeCount;
final int? commentCount;
@@ -70,6 +72,7 @@ class PlayTicket {
.toList(),
tracks: _tracks(json['tracks'], json['playUrl'] as String? ?? ''),
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
posterUrl: _optionalString(json['posterUrl']),
likeCount: json['likeCount'] == null
? null
: jsonToInt(json['likeCount']),
+5
View File
@@ -24,6 +24,7 @@ class ApiClient {
this.tokenRefresher,
this.onUnauthorized,
this.deviceIdReader,
this.platformReader,
}) : _fixedBaseUrl = baseUrl {
_dio = Dio(
BaseOptions(
@@ -40,6 +41,7 @@ class ApiClient {
AuthHeaderInterceptor(
accessTokenReader: accessTokenReader,
deviceIdReader: deviceIdReader,
platformReader: platformReader,
),
const EnvelopeInterceptor(),
NetworkLogInterceptor(),
@@ -67,6 +69,9 @@ class ApiClient {
/// 设备号(`X-Device-Id`):注册风控、后续下载绑定都要用
final Future<String> Function()? deviceIdReader;
/// 客户端平台(`X-Client-Platform`):后台区分 iOS / Android
final String Function()? platformReader;
Future<Object?> get(String path, {Map<String, String>? query}) {
return _request('GET', path, query: query);
}
+12 -1
View File
@@ -32,7 +32,11 @@ class TokenExpiredException implements Exception {
///
/// 每个请求都重新取一次令牌,所以刷新成功后重发的那次会自动带上新令牌。
class AuthHeaderInterceptor extends Interceptor {
AuthHeaderInterceptor({this.accessTokenReader, this.deviceIdReader});
AuthHeaderInterceptor({
this.accessTokenReader,
this.deviceIdReader,
this.platformReader,
});
/// 当前 access token;未登录返回 null 或空串。
final String? Function()? accessTokenReader;
@@ -40,6 +44,9 @@ class AuthHeaderInterceptor extends Interceptor {
/// 设备号(`X-Device-Id`):注册风控、下载绑定都用它。
final Future<String> Function()? deviceIdReader;
/// 客户端平台(`X-Client-Platform`):后台区分 iOS / Android,匿名请求同样要带。
final String Function()? platformReader;
@override
Future<void> onRequest(
RequestOptions options,
@@ -54,6 +61,10 @@ class AuthHeaderInterceptor extends Interceptor {
if (deviceId != null && deviceId.isNotEmpty) {
options.headers['X-Device-Id'] = deviceId;
}
final platform = platformReader?.call() ?? '';
if (platform.isNotEmpty) {
options.headers['X-Client-Platform'] = platform;
}
handler.next(options);
}
}
+5 -1
View File
@@ -56,6 +56,7 @@ class AuthApi {
required String target,
required String code,
required String deviceId,
String countryCode = '',
String platform = '',
String osVersion = '',
String appVersion = '',
@@ -66,6 +67,7 @@ class AuthApi {
'targetType': 'PHONE',
'target': target,
'code': code,
'countryCode': countryCode,
'deviceId': deviceId,
'platform': platform,
'osVersion': osVersion,
@@ -79,6 +81,7 @@ class AuthApi {
required String email,
required String password,
required String deviceId,
String countryCode = '',
String platform = '',
String osVersion = '',
String appVersion = '',
@@ -89,7 +92,7 @@ class AuthApi {
'targetType': 'EMAIL',
'target': email,
'password': password,
'countryCode': 'ID',
'countryCode': countryCode,
'deviceId': deviceId,
'platform': platform,
'osVersion': osVersion,
@@ -134,6 +137,7 @@ class AuthApi {
'platform': platform,
'osVersion': osVersion,
},
skipAuthRetry: true,
);
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
}
+15
View File
@@ -0,0 +1,15 @@
// Author: fruit.com.cn
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
/// 客户端平台,后台只用来区分 iOS / Android。
///
/// 系统版本、机型一律不上报:后台列表需要的只是「这台设备是安卓还是苹果」。
String clientPlatform() {
if (kIsWeb) return 'WEB';
if (Platform.isAndroid) return 'ANDROID';
if (Platform.isIOS) return 'IOS';
return '';
}
+8
View File
@@ -1,5 +1,6 @@
// Author: fruit.com.cn
import '../models/episode_stats.dart';
import '../models/play_ticket.dart';
import 'api_client.dart';
@@ -17,4 +18,11 @@ class PlaybackApi {
if (data is Map<String, dynamic>) return PlayTicket.fromJson(data);
throw const ApiException(-1, '返回数据格式异常');
}
/// 轻量刷新互动计数:不签发地址,也不占用播放票据缓存。
Future<EpisodeStats> episodeStats(String episodeId) async {
final data = await _client.get('/app/episodes/$episodeId/stats');
if (data is Map<String, dynamic>) return EpisodeStats.fromJson(data);
throw const ApiException(-1, '返回数据格式异常');
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ import '../models/page_result.dart';
import '../models/watch_progress.dart';
import 'api_client.dart';
/// 观看进度接口:`/app/watch/*`(契约 §1.5)。全部需要登录态。
/// 观看进度接口:`/app/watch/*`(契约 §1.5)。支持账号或设备身份。
class WatchApi {
const WatchApi(this._client);
@@ -19,21 +19,15 @@ abstract interface class FavoriteRepository {
}
class HttpFavoriteRepository implements FavoriteRepository {
const HttpFavoriteRepository(this._api, {this.isSignedIn});
const HttpFavoriteRepository(this._api);
final LibraryApi _api;
/// 未登录时不请求:收藏属于账号,匿名浏览时列表按空处理(点收藏按钮会先引导登录)。
final bool Function()? isSignedIn;
bool get _signedIn => isSignedIn?.call() ?? true;
@override
Future<bool> toggle(String dramaId) => _api.toggleFavorite(dramaId);
@override
Future<PageResult<Drama>> page({int pageIndex = 1, int pageSize = 20}) async {
if (!_signedIn) return const PageResult();
return _api.favorites(pageIndex: pageIndex, pageSize: pageSize);
}
@@ -1,5 +1,6 @@
// Author: fruit.com.cn
import '../models/episode_stats.dart';
import '../models/play_ticket.dart';
import '../remote/playback_api.dart';
@@ -10,6 +11,9 @@ import '../remote/playback_api.dart';
abstract interface class PlaybackRepository {
Future<PlayTicket> ticketFor(String episodeId, {bool forceRefresh = false});
/// 读取互动计数快照;与 [ticketFor] 分离,避免为了刷新计数重新签发地址。
Future<EpisodeStats> episodeStats(String episodeId);
/// 当前缓存的票据是否还在有效期内(用于"回前台发现过期就重新取")。
bool isFresh(String episodeId);
}
@@ -42,6 +46,10 @@ class HttpPlaybackRepository implements PlaybackRepository {
return ticket;
}
@override
Future<EpisodeStats> episodeStats(String episodeId) =>
_api.episodeStats(episodeId);
@override
bool isFresh(String episodeId) {
final cached = _cache[episodeId];
@@ -65,11 +73,22 @@ class _CachedTicket {
/// 测试与离线场景用:按集返回固定票据,并记录被请求过几次。
class FakePlaybackRepository implements PlaybackRepository {
FakePlaybackRepository({this.ticket, this.error, this.fresh = true});
FakePlaybackRepository({
this.ticket,
this.error,
this.fresh = true,
this.stats,
this.statsError,
Map<String, EpisodeStats>? statsByEpisode,
}) : statsByEpisode = statsByEpisode ?? {};
PlayTicket? ticket;
Object? error;
EpisodeStats? stats;
Object? statsError;
final Map<String, EpisodeStats> statsByEpisode;
final List<String> requests = [];
final List<String> statsRequests = [];
final List<bool> forced = [];
/// 模拟"票据是否还有效":置 false 可验证回前台会重新取。
@@ -95,4 +114,13 @@ class FakePlaybackRepository implements PlaybackRepository {
qualities: const ['AUTO', '720P', '1080P'],
);
}
@override
Future<EpisodeStats> episodeStats(String episodeId) async {
statsRequests.add(episodeId);
if (statsError != null) throw statsError!;
final value = statsByEpisode[episodeId] ?? stats;
if (value != null) return value;
throw StateError('episode stats not configured for $episodeId');
}
}
@@ -35,18 +35,12 @@ abstract interface class WatchHistoryRepository {
}
class HttpWatchHistoryRepository implements WatchHistoryRepository {
const HttpWatchHistoryRepository(this._api, {this.isSignedIn});
const HttpWatchHistoryRepository(this._api);
final WatchApi _api;
/// 未登录时这些接口必然 401:直接短路成"没有记录",让浏览/试看保持匿名可用。
final bool Function()? isSignedIn;
bool get _signedIn => isSignedIn?.call() ?? true;
@override
Future<WatchProgress?> progressFor(String dramaId) async {
if (!_signedIn) return null;
return _api.progressOfDrama(dramaId);
}
@@ -57,7 +51,6 @@ class HttpWatchHistoryRepository implements WatchHistoryRepository {
Duration? duration,
bool finished = false,
}) async {
if (!_signedIn) return null;
return _api.saveProgress(
episodeId: episodeId,
position: position,
@@ -71,19 +64,16 @@ class HttpWatchHistoryRepository implements WatchHistoryRepository {
int pageIndex = 1,
int pageSize = 20,
}) async {
if (!_signedIn) return const PageResult();
return _api.recent(pageIndex: pageIndex, pageSize: pageSize);
}
@override
Future<void> remove(String dramaId) async {
if (!_signedIn) return;
await _api.removeProgress(dramaId);
}
@override
Future<void> clear() async {
if (!_signedIn) return;
await _api.clearProgress();
}
}
@@ -66,7 +66,7 @@ class AllDramasController {
this.categories = const [],
this.tags = const [],
this.dramas = const [],
}) : _api = api;
}) : _api = api; // ignore: prefer_initializing_formals
final AllDramasRemote? _api;
List<ContentCategory> classifications;
@@ -48,6 +48,7 @@ class AuthController extends ChangeNotifier {
email: email,
password: password,
deviceId: await _store.deviceId(),
countryCode: await _store.deviceRegion(),
platform: _platform,
osVersion: _osVersion,
);
@@ -95,6 +96,7 @@ class AuthController extends ChangeNotifier {
target: target,
code: code,
deviceId: await _store.deviceId(),
countryCode: await _store.deviceRegion(),
platform: _platform,
osVersion: _osVersion,
);
+42 -12
View File
@@ -4,6 +4,7 @@ import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/auth_session.dart';
import 'device_id_provider.dart';
/// 令牌与设备号的本地持久化。
///
@@ -11,13 +12,17 @@ import '../models/auth_session.dart';
/// `SharedPreferences.getInstance()` 在新版本里已标注弃用,两套混用还会让
/// widget 测试只 mock 到其中一套。
///
/// 设备号是后端注册风控与后续"下载设备绑定"的依据,所以**首次生成后就固定下来**;
/// 不引 UUID 库(保持极简依赖),用「时间戳 + 随机数」拼一个够用的 id。
/// 设备号优先取系统标识(Android SSAID / iOS IDFV),这样卸载重装后还是同一台设备;
/// 系统标识不可用时才回退到本地生成并持久化的 UUID,保证任何环境都能跑。
class AuthSessionStore {
AuthSessionStore({SharedPreferencesAsync? preferences})
: _preferences = preferences ?? SharedPreferencesAsync();
AuthSessionStore({
SharedPreferencesAsync? preferences,
DeviceIdProvider? deviceIdProvider,
}) : _preferences = preferences ?? SharedPreferencesAsync(),
_deviceIdProvider = deviceIdProvider ?? DeviceIdProvider();
final SharedPreferencesAsync _preferences;
final DeviceIdProvider _deviceIdProvider;
static const _kAccessToken = 'auth.accessToken';
static const _kRefreshToken = 'auth.refreshToken';
@@ -25,21 +30,46 @@ class AuthSessionStore {
static const _kDeviceId = 'device.id';
String? _cachedDeviceId;
String? _cachedRegion;
Future<String> deviceId() async {
if (_cachedDeviceId != null) return _cachedDeviceId!;
var value = await _preferences.getString(_kDeviceId) ?? '';
if (value.isEmpty) {
final random = Random();
value =
'd-${DateTime.now().millisecondsSinceEpoch.toRadixString(36)}-'
'${random.nextInt(1 << 32).toRadixString(36)}';
await _preferences.setString(_kDeviceId, value);
}
final systemId = await _deviceIdProvider.systemDeviceId();
final value = systemId ?? await _localDeviceId();
_cachedDeviceId = value;
return value;
}
/// 设备区域(ISO-2),取不到返回空串;只在注册时作为服务端 IP 解析失败后的兜底。
Future<String> deviceRegion() async {
if (_cachedRegion != null) return _cachedRegion!;
final value = await _deviceIdProvider.deviceRegion() ?? '';
_cachedRegion = value;
return value;
}
/// 系统标识取不到时的兜底:本地 UUIDv4,生成一次后固定下来。
Future<String> _localDeviceId() async {
final stored = await _preferences.getString(_kDeviceId) ?? '';
if (stored.isNotEmpty) return stored;
final generated = 'd-${_uuidV4()}';
await _preferences.setString(_kDeviceId, generated);
return generated;
}
/// UUIDv4:122 位随机,碰撞概率可忽略,不引第三方依赖。
String _uuidV4() {
final random = Random.secure();
final bytes = List<int>.generate(16, (_) => random.nextInt(256));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
String hex(int start, int end) => bytes
.sublist(start, end)
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
.join();
return '${hex(0, 4)}-${hex(4, 6)}-${hex(6, 8)}-${hex(8, 10)}-${hex(10, 16)}';
}
Future<AuthSession?> read() async {
final accessToken = await _preferences.getString(_kAccessToken) ?? '';
final refreshToken = await _preferences.getString(_kRefreshToken) ?? '';
+16 -4
View File
@@ -197,7 +197,10 @@ class CommentController extends ChangeNotifier {
_insertPublished(comment, replyTo);
return OperationResult.success(comment);
} catch (failure) {
return OperationResult.failure(_errorMessage(failure));
return OperationResult.failure(
_errorMessage(failure),
errorCode: failure is ApiException ? failure.code : null,
);
} finally {
submitting = false;
_notify();
@@ -217,7 +220,10 @@ class CommentController extends ChangeNotifier {
return const OperationResult.success();
} catch (failure) {
_restoreComment(comment, location);
return OperationResult.failure(_errorMessage(failure));
return OperationResult.failure(
_errorMessage(failure),
errorCode: failure is ApiException ? failure.code : null,
);
} finally {
_deletingCommentIds.remove(comment.id);
_notify();
@@ -253,7 +259,10 @@ class CommentController extends ChangeNotifier {
return OperationResult.success(result);
} catch (failure) {
_replaceComment(current);
return OperationResult.failure(_errorMessage(failure));
return OperationResult.failure(
_errorMessage(failure),
errorCode: failure is ApiException ? failure.code : null,
);
} finally {
_likingCommentIds.remove(comment.id);
_notify();
@@ -277,7 +286,10 @@ class CommentController extends ChangeNotifier {
);
return OperationResult.success(reportId);
} catch (failure) {
return OperationResult.failure(_errorMessage(failure));
return OperationResult.failure(
_errorMessage(failure),
errorCode: failure is ApiException ? failure.code : null,
);
}
}
@@ -0,0 +1,50 @@
// Author: fruit.com.cn
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// 读取系统级设备标识,两端都不需要任何权限。
///
/// - Android:SSAID(`Settings.Secure.ANDROID_ID`),卸载重装不变;
/// - iOS:IDFV(`identifierForVendor`),卸载本 App 不变,同厂商应用全删才会变。
///
/// 两端都由原生侧提供,不引插件:项目 iOS 走 SPM,避免混入 CocoaPods。
/// 取不到(Web、测试环境、通道异常)时返回 null,由调用方回退到本地生成的 id。
class DeviceIdProvider {
static const MethodChannel _channel = MethodChannel(
'com.stormg.lumadrama/device',
);
Future<String?> systemDeviceId() async {
if (kIsWeb) return null;
try {
if (Platform.isAndroid) {
final ssaid = await _channel.invokeMethod<String>('ssaid');
if (ssaid != null && ssaid.isNotEmpty) return 'a-$ssaid';
}
if (Platform.isIOS) {
final idfv = await _channel.invokeMethod<String>('idfv');
if (idfv != null && idfv.isNotEmpty) return 'i-$idfv';
}
} catch (_) {
// 原生通道不可用(widget 测试)时走本地兜底
}
return null;
}
/// 设备所在区域(ISO-2),仅用于服务端 IP 解析失败时兜底注册国家。
/// Android 依次取网络运营商 / SIM 卡 / 系统语言的国家,iOS 取系统 region。
Future<String?> deviceRegion() async {
if (kIsWeb) return null;
try {
final region = await _channel.invokeMethod<String>('region');
final value = region?.trim().toUpperCase() ?? '';
if (value.length == 2) return value;
} catch (_) {
// 原生通道不可用(widget 测试)时返回 null,由服务端兜底
}
return null;
}
}
+106 -4
View File
@@ -3,6 +3,7 @@
import 'package:flutter/foundation.dart';
import '../models/drama.dart';
import '../remote/api_client.dart';
import '../repositories/favorite_repository.dart';
/// 收藏状态:**以服务端为准**。
@@ -17,6 +18,7 @@ class FavoriteController extends ChangeNotifier {
final FavoriteRepository _repository;
final int pageSize;
final Set<String> _saved = {};
final Map<String, int> _favoriteCounts = {};
List<Drama> cards = const [];
int total = 0;
bool loading = false;
@@ -24,6 +26,7 @@ class FavoriteController extends ChangeNotifier {
bool hasMore = false;
String? error;
String? loadMoreError;
int? lastErrorCode;
int _pageIndex = 0;
int _requestSeq = 0;
bool _disposed = false;
@@ -32,6 +35,53 @@ class FavoriteController extends ChangeNotifier {
bool isSaved(String dramaId) => _saved.contains(dramaId);
/// 当前剧收藏数;包含本地 toggle 增量。
int? favoriteCount(String dramaId) => _favoriteCounts[dramaId];
/// 首次展示时缓存卡片基数;之后统一由本控制器维护,避免页面各存一份。
int? favoriteCountFor(Drama drama) {
final current = _favoriteCounts[drama.id];
if (current != null) return current;
final fallback = drama.favoriteCount;
if (fallback == null) return null;
final normalized = fallback < 0 ? 0 : fallback;
_favoriteCounts[drama.id] = normalized;
return normalized;
}
/// 用 stats/detail 的服务端快照校准唯一状态和计数。
void applyServerState(
String dramaId, {
required bool saved,
int? favoriteCount,
}) {
var changed = _saved.contains(dramaId) != saved;
if (saved) {
_saved.add(dramaId);
} else {
_saved.remove(dramaId);
}
if (favoriteCount != null) {
final normalized = favoriteCount < 0 ? 0 : favoriteCount;
changed = changed || _favoriteCounts[dramaId] != normalized;
_favoriteCounts[dramaId] = normalized;
}
if (changed) notify();
}
/// 详情等只有计数、没有当前收藏状态的接口使用。
void applyServerCount(
String dramaId,
int? favoriteCount, {
bool notify = true,
}) {
if (favoriteCount == null) return;
final normalized = favoriteCount < 0 ? 0 : favoriteCount;
if (_favoriteCounts[dramaId] == normalized) return;
_favoriteCounts[dramaId] = normalized;
if (notify) this.notify();
}
void notify() {
if (!_disposed) notifyListeners();
}
@@ -43,6 +93,7 @@ class FavoriteController extends ChangeNotifier {
loadingMore = false;
error = null;
loadMoreError = null;
lastErrorCode = null;
notify();
try {
final page = await _repository.page(pageIndex: 1, pageSize: pageSize);
@@ -52,12 +103,14 @@ class FavoriteController extends ChangeNotifier {
_saved
..clear()
..addAll(list.map((drama) => drama.id));
_rememberCardCounts(list);
total = page.total;
_pageIndex = 1;
hasMore = page.list.isNotEmpty && cards.length < total;
} catch (_) {
} catch (failure) {
if (!_disposed && request == _requestSeq) {
error = 'favoritesError';
if (failure is ApiException) lastErrorCode = failure.code;
}
} finally {
if (!_disposed && request == _requestSeq) {
@@ -73,6 +126,7 @@ class FavoriteController extends ChangeNotifier {
final request = ++_requestSeq;
loadingMore = true;
loadMoreError = null;
lastErrorCode = null;
notify();
try {
final page = await _repository.page(
@@ -86,12 +140,14 @@ class FavoriteController extends ChangeNotifier {
).where((drama) => known.add(drama.id)).toList(growable: false);
cards = [...cards, ...appended];
_saved.addAll(appended.map((drama) => drama.id));
_rememberCardCounts(appended);
total = page.total;
_pageIndex += 1;
hasMore = page.list.isNotEmpty && cards.length < total;
} catch (_) {
} catch (failure) {
if (!_disposed && request == _requestSeq) {
loadMoreError = 'favoritesError';
if (failure is ApiException) lastErrorCode = failure.code;
}
} finally {
if (!_disposed && request == _requestSeq) {
@@ -101,18 +157,23 @@ class FavoriteController extends ChangeNotifier {
}
}
/// 未登录时不要调用(服务端要求登录态)。
/// 每次切换都以接口状态为准;匿名请求由设备号归属。
///
/// [card] 是当前剧的卡片(播放页/详情页手上就有):收藏成功时直接放进列表,
/// 这样"收藏完打开我的收藏"能立刻看到,不必等下一次整表刷新。
Future<bool> toggle(String dramaId, {Drama? card}) async {
lastErrorCode = null;
final wasSaved = _saved.contains(dramaId);
final previousCount = card == null
? favoriteCount(dramaId)
: favoriteCountFor(card);
final previousCards = cards;
final previousTotal = total;
final previousHasMore = hasMore;
// 乐观更新
if (wasSaved) {
_saved.remove(dramaId);
_stepCount(dramaId, -1);
if (cards.any((drama) => drama.id == dramaId)) {
cards = cards.where((drama) => drama.id != dramaId).toList();
total = total > 0 ? total - 1 : 0;
@@ -120,6 +181,7 @@ class FavoriteController extends ChangeNotifier {
}
} else {
_saved.add(dramaId);
_stepCount(dramaId, 1);
}
notify();
try {
@@ -128,6 +190,7 @@ class FavoriteController extends ChangeNotifier {
if (saved) {
_saved.add(dramaId);
if (wasSaved) {
_restoreCount(dramaId, previousCount);
cards = previousCards;
total = previousTotal;
hasMore = previousHasMore;
@@ -138,6 +201,9 @@ class FavoriteController extends ChangeNotifier {
}
} else {
_saved.remove(dramaId);
if (!wasSaved) {
_restoreCount(dramaId, previousCount);
}
if (cards.any((drama) => drama.id == dramaId)) {
cards = cards.where((drama) => drama.id != dramaId).toList();
total = total > 0 ? total - 1 : 0;
@@ -146,7 +212,7 @@ class FavoriteController extends ChangeNotifier {
}
notify();
return true;
} catch (_) {
} catch (failure) {
// 回滚
cards = previousCards;
total = previousTotal;
@@ -156,7 +222,9 @@ class FavoriteController extends ChangeNotifier {
} else {
_saved.remove(dramaId);
}
_restoreCount(dramaId, previousCount);
notify();
if (failure is ApiException) lastErrorCode = failure.code;
return false;
}
}
@@ -170,9 +238,13 @@ class FavoriteController extends ChangeNotifier {
final previousHasMore = hasMore;
final removed = cards.where((drama) => ids.contains(drama.id)).toList();
if (removed.isEmpty) return true;
final previousCounts = {
for (final drama in removed) drama.id: _favoriteCounts[drama.id],
};
cards = cards.where((drama) => !ids.contains(drama.id)).toList();
for (final id in ids) {
_saved.remove(id);
_stepCount(id, -1);
}
total = total > removed.length ? total - removed.length : 0;
hasMore = cards.length < total;
@@ -187,6 +259,9 @@ class FavoriteController extends ChangeNotifier {
for (final drama in removed) {
_saved.add(drama.id);
}
for (final entry in previousCounts.entries) {
_restoreCount(entry.key, entry.value);
}
notify();
return false;
}
@@ -197,7 +272,9 @@ class FavoriteController extends ChangeNotifier {
final index = cards.indexWhere((drama) => drama.id == dramaId);
if (index < 0) return true;
final removed = cards[index];
final previousCount = _favoriteCounts[dramaId];
_saved.remove(dramaId);
_stepCount(dramaId, -1);
final next = [...cards]..removeAt(index);
cards = next;
total = total > 0 ? total - 1 : 0;
@@ -214,6 +291,7 @@ class FavoriteController extends ChangeNotifier {
);
cards = restored;
_saved.add(dramaId);
_restoreCount(dramaId, previousCount);
total += 1;
hasMore = cards.length < total;
notify();
@@ -244,6 +322,30 @@ class FavoriteController extends ChangeNotifier {
];
}
void _rememberCardCounts(List<Drama> dramas) {
for (final drama in dramas) {
final count = drama.favoriteCount;
if (count != null && !_favoriteCounts.containsKey(drama.id)) {
_favoriteCounts[drama.id] = count < 0 ? 0 : count;
}
}
}
void _stepCount(String dramaId, int delta) {
final current = _favoriteCounts[dramaId];
if (current == null) return;
final next = current + delta;
_favoriteCounts[dramaId] = next < 0 ? 0 : next;
}
void _restoreCount(String dramaId, int? count) {
if (count == null) {
_favoriteCounts.remove(dramaId);
} else {
_favoriteCounts[dramaId] = count;
}
}
@override
void dispose() {
_disposed = true;
@@ -33,6 +33,7 @@ class HomeFeedController extends ChangeNotifier {
String? get cursor => _state(_channel).cursor;
bool get hasMore => _state(_channel).hasMore;
bool get loaded => _state(_channel).loaded;
bool get isLoading => _state(_channel).loading;
bool get loadingMore => _state(_channel).loadingMore;
bool get loadingFirstPage => !loaded && _state(_channel).loading;
@@ -40,6 +40,24 @@ class InteractionController extends ChangeNotifier {
/// 该集服务端最新点赞数。
int? episodeLikeCount(String episodeId) => _episodeLikeCounts[episodeId];
/// 用轻量统计快照校准当前用户的分集点赞状态与计数。
void applyEpisodeStats(
String episodeId, {
required bool liked,
required int likeCount,
}) {
final changed =
_likedEpisodeIds.contains(episodeId) != liked ||
_episodeLikeCounts[episodeId] != likeCount;
if (liked) {
_likedEpisodeIds.add(episodeId);
} else {
_likedEpisodeIds.remove(episodeId);
}
_episodeLikeCounts[episodeId] = likeCount;
if (changed) _notify();
}
/// 乐观切换剧集点赞,失败时回滚并以服务端返回状态校准。
Future<OperationResult<LikeToggleResult>> toggleDramaLike(String dramaId) =>
_toggleLike(
@@ -97,7 +115,10 @@ class InteractionController extends ChangeNotifier {
} else {
likedIds.remove(id);
}
return OperationResult.failure(_errorMessage(failure));
return OperationResult.failure(
_errorMessage(failure),
errorCode: failure is ApiException ? failure.code : null,
);
} finally {
busyIds.remove(id);
_notify();
@@ -121,7 +142,10 @@ class InteractionController extends ChangeNotifier {
);
return OperationResult.success(reportId);
} catch (failure) {
return OperationResult.failure(_errorMessage(failure));
return OperationResult.failure(
_errorMessage(failure),
errorCode: failure is ApiException ? failure.code : null,
);
}
}
+62 -16
View File
@@ -13,14 +13,40 @@ class PlaybackCoordinator {
Future<bool> _acquire(PlaybackSession session, bool Function() valid) {
final result = _handoff.then((_) async {
if (!valid()) return false;
final previous = _owner;
if (kDebugMode) {
debugPrint(
'[player-coordinator] phase=acquire '
'session=${identityHashCode(session)} owner=${session.owner.name} '
'previous=${previous == null ? '-' : identityHashCode(previous)} '
'previousOwner=${previous?.owner.name ?? '-'} '
'previousLive=${previous?.livePlayerCount ?? 0} '
'same=${identical(previous, session)}',
);
}
if (_owner != session) {
final previous = _owner;
if (previous != null && previous.owner != session.owner) {
if (kDebugMode) {
debugPrint(
'[player-owner] phase=reject-coordinator-handoff '
'owner=${session.owner.name} '
'activeOwner=${previous.owner.name}',
);
}
return false;
}
await previous?._releasePlayers();
if (previous != null && previous.livePlayerCount != 0) return false;
_owner = null;
if (!valid()) return false;
_owner = session;
}
if (kDebugMode) {
debugPrint(
'[player-coordinator] phase=acquired '
'session=${identityHashCode(session)} live=${session.livePlayerCount}',
);
}
return true;
});
_handoff = result.then<void>((_) {});
@@ -49,13 +75,21 @@ Future<void> _parkNeighbors(
_PlayerSlot? warmNext,
_PlayerSlot? warmPrevious,
) async {
await _placeNeighbor(session, old);
await _placeNeighbor(session, warmNext);
await _placeNeighbor(session, warmPrevious);
await _placeNeighbor(session, old, roleHint: 'old-current');
await _placeNeighbor(session, warmNext, roleHint: 'next');
await _placeNeighbor(session, warmPrevious, roleHint: 'previous');
}
Future<void> _placeNeighbor(PlaybackSession session, _PlayerSlot? slot) async {
Future<void> _placeNeighbor(
PlaybackSession session,
_PlayerSlot? slot, {
required String roleHint,
}) async {
if (slot == null || slot == session._active || slot.retiring) return;
if (slot.owner != session.owner) {
session._logOwnerRejection('park', slot);
return;
}
if (session._next == null && slot.index == session._nextIndex) {
session._next = slot;
return;
@@ -64,18 +98,22 @@ Future<void> _placeNeighbor(PlaybackSession session, _PlayerSlot? slot) async {
session._previous = slot;
return;
}
await session._retire(slot);
await session._retire(slot, trigger: 'park-neighbor', roleHint: roleHint);
}
/// 当前集已经出画后,静默准备上一集和下一集。
void _warmNeighbors(PlaybackSession session) {
/// 当前集已经出画后,按手势方向静默准备上一集和下一集。
void _warmNeighbors(PlaybackSession session, {bool preferredNext = true}) {
final request = session._generation;
session._preloadTask = () async {
await Future.wait([
_warmOne(session, request, session._nextIndex, next: true),
_warmOne(session, request, session._previousIndex, next: false),
]);
}();
final nextTask = _warmOne(session, request, session._nextIndex, next: true);
final previousTask = _warmOne(
session,
request,
session._previousIndex,
next: false,
);
session._preloadTask = Future.wait(
preferredNext ? [nextTask, previousTask] : [previousTask, nextTask],
).then<void>((_) {});
}
Future<void> _warmOne(
@@ -100,7 +138,11 @@ Future<void> _warmOne(
await session._enqueue(() async {
if (!_stillHeld(session, candidate, next: next)) return;
_clearNeighbor(session, next: next);
await session._retire(candidate);
await session._retire(
candidate,
trigger: 'warm-failure',
roleHint: next ? 'next' : 'previous',
);
});
}
@@ -117,7 +159,11 @@ Future<_PlayerSlot?> _allocateNeighbor(
final current = next ? session._next : session._previous;
if (!allowed || current?.index != index) {
_clearNeighbor(session, next: next);
await session._retire(current);
await session._retire(
current,
trigger: 'warm-slot-invalid',
roleHint: next ? 'next' : 'previous',
);
}
if (!_canAllocate(session, request, allowed: allowed, next: next)) {
return;
+149 -47
View File
@@ -8,6 +8,7 @@ import '../models/player_port.dart';
import 'video_player_port.dart';
part 'playback_neighbors.dart';
part 'playback_session_controls.dart';
/// 新纹理第一帧常是黑的,旧画面只盖住这一小段。
const Duration _qualityHandoffHold = Duration(milliseconds: 200);
@@ -16,6 +17,8 @@ typedef PlayerFactory = PlayerPort Function(Episode episode);
typedef PlayerPreparation =
Future<void> Function(Episode episode, PlayerPort player);
enum PlaybackSessionOwner { home, player }
/// Owns current plus previous/next frames; allocation stays serialized.
class PlaybackSession extends ChangeNotifier {
PlaybackSession({
@@ -26,6 +29,8 @@ class PlaybackSession extends ChangeNotifier {
this.activate,
PlaybackCoordinator? coordinator,
this.waitForFrame,
this.owner = PlaybackSessionOwner.player,
this.dramaIdAt,
}) : _coordinator = coordinator ?? PlaybackCoordinator();
final List<Episode> episodes;
@@ -38,6 +43,8 @@ class PlaybackSession extends ChangeNotifier {
/// Runs only when a slot becomes current (e.g. progress listeners).
final PlayerPreparation? activate;
final Future<void> Function()? waitForFrame;
final PlaybackSessionOwner owner;
final String? Function(int index)? dramaIdAt;
final PlaybackCoordinator _coordinator;
final Set<_PlayerSlot> _live = {};
_PlayerSlot? _active;
@@ -77,9 +84,18 @@ class PlaybackSession extends ChangeNotifier {
bool get canAutoAdvance => _mayPlay && !_loading && active != null;
bool get isLocked => !canPlay(currentEpisode);
String? get error => _error;
bool get debugAppResumed => _appResumed;
bool get debugRouteVisible => _routeVisible;
bool get debugOverlayOpen => _overlayOpen;
bool get debugVisible => _visible;
bool get debugMayPlay => _mayPlay;
// Includes initialization and asynchronous disposal, until native release ends.
int get livePlayerCount => _live.length;
bool get activeSlotActivated => _active?.activated ?? false;
bool get activeSlotPlaying => _active?.playing ?? false;
int? get preloadedIndex => _next?.prepared == true ? _next?.index : null;
int? get previousPreloadedIndex =>
_previous?.prepared == true ? _previous?.index : null;
Future<void> get playbackSettled => _operations;
Future<void> get preloadSettled => _preloadTask;
@@ -106,15 +122,6 @@ class PlaybackSession extends ChangeNotifier {
return null;
}
/// 清晰度切换时盖住黑帧的旧播放器。只在仍由会话持有时交给界面。
PlayerPort? handoffAt(int index) {
final slot = _handoff;
if (_closed || slot == null || slot.retiring || slot.index != index) {
return null;
}
return slot.player;
}
/// 队列重排后把当前仍在播放的 slot 映射到新索引,不重新创建播放器。
void remapCurrentIndex(int index, {int? preloadIndex, int? previousIndex}) {
if (_closed || index < 0 || index >= episodes.length) return;
@@ -136,8 +143,12 @@ class PlaybackSession extends ChangeNotifier {
_notify();
unawaited(
_enqueue(() async {
await _retire(staleNext);
await _retire(stalePrevious);
await _retire(staleNext, trigger: 'remap-stale-next', roleHint: 'next');
await _retire(
stalePrevious,
trigger: 'remap-stale-previous',
roleHint: 'previous',
);
}),
);
if (_visible && !_overlayOpen) _warmNeighbors(this);
@@ -165,7 +176,12 @@ class PlaybackSession extends ChangeNotifier {
if (_live.length >= maxLivePlayers) {
throw StateError('Playback resource limit reached');
}
final slot = _PlayerSlot(index, factory(episodes[index]));
final slot = _PlayerSlot(
index,
factory(episodes[index]),
owner: owner,
dramaId: dramaIdAt?.call(index),
);
_live.add(slot);
slot.ready = () async {
try {
@@ -183,8 +199,23 @@ class PlaybackSession extends ChangeNotifier {
return slot;
}
Future<void> _retire(_PlayerSlot? slot) async {
if (slot == null || !_live.contains(slot)) return;
Future<void> _retire(
_PlayerSlot? slot, {
required String trigger,
String? roleHint,
}) async {
if (slot == null) return;
if (slot.owner != owner) {
_logOwnerRejection('retire', slot);
return;
}
if (!_live.contains(slot)) return;
final role = _slotRole(slot, roleHint: roleHint);
final video = slot.player is VideoPlayerPort
? slot.player as VideoPlayerPort
: null;
final value = video?.controller.value;
final slotPlaying = slot.playing;
slot.retiring = true;
final cleared =
_active == slot ||
@@ -203,6 +234,19 @@ class PlaybackSession extends ChangeNotifier {
} finally {
await slot.player.dispose();
_live.remove(slot);
if (kDebugMode) {
debugPrint(
'[player-slot] slot_released role=$role owner=${slot.owner.name} '
'selectOwner=$owner drama=${slot.dramaId ?? '-'} '
'episodeIndex=${slot.index} '
'controller=${_playerIdentity(slot.player)} '
'slotPlaying=${slotPlaying ? 1 : 0} '
'isPlaying=${value?.isPlaying == true ? 1 : 0} '
'position=${value?.position.inMilliseconds ?? '-'} '
'currentIndex=$_currentIndex generation=$_generation '
'trigger=$trigger',
);
}
}
}
@@ -212,11 +256,23 @@ class PlaybackSession extends ChangeNotifier {
int index, {
int? preloadIndex,
int? previousIndex,
bool? userWantsPlay,
}) async {
if (_closed || index < 0 || index >= episodes.length) return;
// 切到另一集时,上一集按下的暂停不跟着走:滑过去就应该自动播放。
// 重复选中同一集(例如页面重新可见)不在这里恢复,尊重用户按下的暂停。
if (!_selected || index != _currentIndex) {
if (kDebugMode) {
debugPrint(
'[player-session] phase=select-enter session=${identityHashCode(this)} '
'owner=${owner.name} index=$index user=$_userWantsPlay '
'selected=$_selected current=$_currentIndex '
'appResumed=$_appResumed routeVisible=$_routeVisible '
'overlayOpen=$_overlayOpen visible=$_visible mayPlay=$_mayPlay '
'live=${_live.length}',
);
}
// 切换到不同剧集时恢复播放;仍停留在同一集时保留用户暂停。
if (userWantsPlay != null) {
_userWantsPlay = userWantsPlay;
} else if (!_selected || index != _currentIndex) {
_userWantsPlay = true;
}
final request = ++_generation;
@@ -247,7 +303,7 @@ class PlaybackSession extends ChangeNotifier {
_PlayerSlot? target;
await _enqueue(() async {
if (_closed || request != _generation) return;
await _retire(_handoff);
await _retire(_handoff, trigger: 'select-handoff');
final old = _active;
if (old != null &&
old.index == index &&
@@ -256,7 +312,10 @@ class PlaybackSession extends ChangeNotifier {
target = old;
return;
}
if (old != null) await old.player.pause();
if (old != null) {
await old.player.pause();
old.playing = false;
}
final warmNext = _next;
final warmPrevious = _previous;
_active = null;
@@ -266,6 +325,7 @@ class PlaybackSession extends ChangeNotifier {
_usableWarm(this, warmNext, index) ??
_usableWarm(this, warmPrevious, index);
if (warm != null) {
warm.reusedWarm = true;
target = _active = warm;
_loading = !warm.prepared;
_notify();
@@ -314,7 +374,9 @@ class PlaybackSession extends ChangeNotifier {
await _enqueue(() => _start(slot, request));
await Future<void>.delayed(_qualityHandoffHold);
if (previous != null && _handoff == previous && _active == slot) {
await _enqueue(() => _retire(previous));
await _enqueue(
() => _retire(previous, trigger: 'quality-handoff-complete'),
);
}
if (!_closed && request == _generation) _warmNeighbors(this);
return _active == slot && slot.failure == null;
@@ -326,8 +388,8 @@ class PlaybackSession extends ChangeNotifier {
if (_closed || request != _generation || _active == null) return;
final warm = _next;
_next = null;
await _retire(_handoff);
await _retire(warm);
await _retire(_handoff, trigger: 'replacement-handoff');
await _retire(warm, trigger: 'replacement-next');
if (_closed || request != _generation || _active == null) return;
try {
created = _create(index);
@@ -354,7 +416,9 @@ class PlaybackSession extends ChangeNotifier {
Future<void> _dropReplacement(_PlayerSlot slot) {
return _enqueue(() async {
if (_live.contains(slot)) await _retire(slot);
if (_live.contains(slot)) {
await _retire(slot, trigger: 'replacement-drop');
}
});
}
@@ -369,7 +433,10 @@ class PlaybackSession extends ChangeNotifier {
_handoff = previous;
_active = slot;
shown = true;
if (previous != null) await previous!.player.pause();
if (previous != null) {
await previous!.player.pause();
previous!.playing = false;
}
_notify();
});
if (!shown || _active != slot) return null;
@@ -413,6 +480,22 @@ class PlaybackSession extends ChangeNotifier {
Future<void> _applyPlayback(_PlayerSlot slot) async {
if (_closed || _active != slot || !slot.activated) return;
final shouldPlay = _mayPlay && slot.index == _currentIndex && !isLocked;
final video = slot.player is VideoPlayerPort
? slot.player as VideoPlayerPort
: null;
if (kDebugMode) {
debugPrint(
'[player-session] phase=apply-playback '
'session=${identityHashCode(this)} owner=${owner.name} '
'index=${slot.index} shouldPlay=$shouldPlay user=$_userWantsPlay '
'appResumed=$_appResumed routeVisible=$_routeVisible '
'overlayOpen=$_overlayOpen locked=$isLocked '
'player=${identityHashCode(slot.player)} '
'controller=${video == null ? '-' : identityHashCode(video.controller)} '
'isPlaying=${video?.controller.value.isPlaying ?? '-'} '
'slotPlaying=${slot.playing}',
);
}
if (shouldPlay == slot.playing) return;
if (shouldPlay) {
await slot.player.play();
@@ -420,27 +503,15 @@ class PlaybackSession extends ChangeNotifier {
await slot.player.pause();
}
slot.playing = shouldPlay;
}
void setAppResumed(bool value) {
_appResumed = value;
_syncPlayback();
}
void setRouteVisible(bool value) {
_routeVisible = value;
_syncPlayback();
}
void setOverlayOpen(bool value) {
_overlayOpen = value;
_syncPlayback();
}
void setUserWantsPlay(bool value) {
_userWantsPlay = value;
_syncPlayback();
_notify();
if (kDebugMode) {
debugPrint(
'[player-session] phase=apply-playback-result '
'session=${identityHashCode(this)} index=${slot.index} '
'shouldPlay=$shouldPlay '
'isPlaying=${video?.controller.value.isPlaying ?? '-'} '
'slotPlaying=${slot.playing}',
);
}
}
void _syncPlayback() {
@@ -467,7 +538,7 @@ class PlaybackSession extends ChangeNotifier {
_loading = false;
_notify();
for (final slot in _live.toList()) {
await _retire(slot);
await _retire(slot, trigger: 'session-release-all');
}
});
}
@@ -476,6 +547,23 @@ class PlaybackSession extends ChangeNotifier {
if (!_closed) notifyListeners();
}
String _slotRole(_PlayerSlot slot, {String? roleHint}) {
if (identical(slot, _active)) return 'current';
if (identical(slot, _previous)) return 'previous';
if (identical(slot, _next)) return 'next';
if (identical(slot, _handoff)) return 'handoff';
return roleHint ?? 'unassigned';
}
void _logOwnerRejection(String phase, _PlayerSlot slot) {
if (!kDebugMode) return;
debugPrint(
'[player-owner] phase=reject-$phase expected=${owner.name} '
'actual=${slot.owner.name} drama=${slot.dramaId ?? '-'} '
'episodeIndex=${slot.index} controller=${_playerIdentity(slot.player)}',
);
}
Future<void> close() async {
if (_closed) return;
_closed = true;
@@ -486,13 +574,27 @@ class PlaybackSession extends ChangeNotifier {
}
class _PlayerSlot {
_PlayerSlot(this.index, this.player);
_PlayerSlot(
this.index,
this.player, {
required this.owner,
required this.dramaId,
});
int index;
final PlayerPort player;
final PlaybackSessionOwner owner;
final String? dramaId;
late final Future<void> ready;
bool prepared = false;
bool activated = false;
bool playing = false;
bool retiring = false;
bool reusedWarm = false;
Object? failure;
}
String _playerIdentity(PlayerPort player) {
return player is VideoPlayerPort
? '${identityHashCode(player.controller)}'
: '${identityHashCode(player)}';
}
@@ -0,0 +1,133 @@
// Author: fruit.com.cn
part of 'playback_session.dart';
/// 播放会话的可见性、用户意图与相邻集预热控制。
extension PlaybackSessionControls on PlaybackSession {
/// 滑动手势开始时按方向优先准备相邻集,不改变当前集播放状态。
void prewarmNeighbors({required bool forward}) {
if (!_visible || _overlayOpen || _active?.prepared != true) return;
_warmNeighbors(this, preferredNext: forward);
}
/// 路由交接时同步暂停当前原生播放器,controller 仍由 session 持有。
Future<void> pauseForRouteHandoff() {
if (_closed) return Future<void>.value();
_routeVisible = false;
return _enqueue(() async {
final slot = _active;
if (slot == null) return;
await slot.player.pause();
slot.playing = false;
});
}
/// 路由恢复可见后立即同步当前 controller,并等待原生播放状态落地。
Future<void> resumeForRouteHandoff() {
if (_closed) return Future<void>.value();
_routeVisible = true;
return _enqueue(() async {
final slot = _active;
if (kDebugMode) {
debugPrint(
'[feed-handoff] phase=resume slot=${slot?.index} '
'activated=${slot?.activated} playing=${slot?.playing} '
'retiring=${slot?.retiring} current=$_currentIndex '
'visible=$_visible user=$_userWantsPlay loading=$_loading',
);
}
if (slot == null || slot.retiring) return;
if (!slot.activated) {
try {
await activate?.call(episodes[slot.index], slot.player);
} catch (error) {
if (kDebugMode) {
debugPrint('[feed-handoff] phase=activation-failed error=$error');
}
}
if (_closed || _active != slot || slot.retiring) {
if (kDebugMode) {
debugPrint(
'[feed-handoff] phase=activation-aborted closed=$_closed '
'activeSame=${identical(_active, slot)} retiring=${slot.retiring}',
);
}
return;
}
slot.activated = true;
}
await _applyPlayback(slot);
if (_visible && !_overlayOpen && !_loading) _warmNeighbors(this);
if (kDebugMode) {
debugPrint(
'[feed-handoff] phase=resumed activated=${slot.activated} '
'playing=${slot.playing}',
);
}
});
}
/// 选中锁定集时立即停播并释放所有原生播放器,不创建新片源。
Future<void> selectLocked(
int index, {
int? preloadIndex,
int? previousIndex,
}) {
if (_closed || index < 0 || index >= episodes.length) {
return Future<void>.value();
}
_generation++;
_selected = false;
_currentIndex = index;
_rememberNeighbors(preloadIndex, previousIndex);
_loading = false;
_error = null;
_userWantsPlay = false;
_notify();
return _releasePlayers();
}
/// 清晰度切换时盖住黑帧的旧播放器。只在仍由会话持有时交给界面。
PlayerPort? handoffAt(int index) {
final slot = _handoff;
if (_closed || slot == null || slot.retiring || slot.index != index) {
return null;
}
return slot.player;
}
/// 当前索引是否复用了已预热的播放器槽。
bool reusedWarmAt(int index) {
for (final slot in [_active, _next, _previous]) {
if (slot != null && !slot.retiring && slot.index == index) {
return slot.reusedWarm;
}
}
return false;
}
/// 同步应用前台状态并恢复或暂停当前集。
void setAppResumed(bool value) {
_appResumed = value;
_syncPlayback();
}
/// 同步播放器路由是否可见。
void setRouteVisible(bool value) {
_routeVisible = value;
_syncPlayback();
}
/// 同步浮层是否遮挡播放器。
void setOverlayOpen(bool value) {
_overlayOpen = value;
_syncPlayback();
}
/// 记录用户播放意图;切换剧集时会在 [PlaybackSession.select] 中恢复播放。
void setUserWantsPlay(bool value) {
_userWantsPlay = value;
_syncPlayback();
_notify();
}
}
@@ -9,7 +9,7 @@ import '../../config/app_config.dart';
import 'sprite_thumbnail_asset_loader.dart';
const Duration spriteVttCacheTtl = Duration(minutes: 10);
const int spriteImageCacheCapacity = 2;
const int spriteImageCacheCapacity = 1;
/// 单个 VTT cue 对应的 sprite 裁剪区域。
class SpriteThumbnailCue {
@@ -132,36 +132,36 @@ class SpriteThumbnailAxisService extends ChangeNotifier
SpriteThumbnailAxisService({
SpriteThumbnailAssetLoader? loader,
this.cacheTtl = spriteVttCacheTtl,
this.spriteCacheCapacity = spriteImageCacheCapacity,
DateTime Function()? now,
}) : _loader = loader ?? DioSpriteThumbnailAssetLoader(),
_now = now ?? DateTime.now;
final SpriteThumbnailAssetLoader _loader;
final Duration cacheTtl;
final int spriteCacheCapacity;
final DateTime Function() _now;
final Map<String, _CachedAxis> _axisCache = {};
final Map<String, Future<SpriteThumbnailAxis>> _axisRequests = {};
final LinkedHashMap<String, _CachedSprite> _spriteCache = LinkedHashMap();
final Map<String, Future<_CachedSprite?>> _spriteRequests = {};
final Set<String> _failedSprites = {};
String? _activeAxisUrl;
int _axisGeneration = 0;
bool _disposed = false;
@visibleForTesting
int get spriteCacheSize => _spriteCache.length;
@visibleForTesting
List<String> get spriteCacheKeys => _spriteCache.keys.toList();
List<String> get spriteCacheKeys => _spriteCache.keys
.map((url) => Uri.tryParse(url)?.pathSegments.lastOrNull ?? url)
.toList();
/// 播放器就绪时预取当前 cue 与相邻 sprite,拖动帧不触发网络或解码。
/// 播放器就绪时预取当前 cue;容量大于 1 时顺带预取相邻 sprite。
@override
Future<void> prepareAt(String? thumbnailsUrl, Duration position) async {
final url = _normalizeUrl(thumbnailsUrl);
if (_disposed || url == null) return;
_activateAxis(url);
final axis = await _loadAxis(url);
if (_disposed || _activeAxisUrl != url) return;
if (_disposed) return;
for (final cue in _prefetchCues(axis, position)) {
await _ensureSprite(axis, cue);
}
@@ -170,7 +170,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
@override
bool hasAxis(String? thumbnailsUrl) {
final url = _normalizeUrl(thumbnailsUrl);
if (url == null || url != _activeAxisUrl) return false;
if (url == null) return false;
return _readAxis(url) != null;
}
@@ -180,12 +180,14 @@ class SpriteThumbnailAxisService extends ChangeNotifier
Duration position,
) {
final url = _normalizeUrl(thumbnailsUrl);
if (url == null || url != _activeAxisUrl) return null;
if (url == null) return null;
final axis = _readAxis(url);
if (axis == null) return null;
final cue = selectSpriteThumbnailCue(axis.cues, position);
if (cue == null) return null;
final cached = _readSprite(cue.spriteFile);
final cached = _readSprite(
axis.resolveSpriteUri(cue.spriteFile).toString(),
);
if (cached == null) return null;
final sourceRect = _scaledSourceRect(cached, cue.sourceRect);
if (sourceRect == null) return null;
@@ -206,13 +208,6 @@ class SpriteThumbnailAxisService extends ChangeNotifier
super.dispose();
}
void _activateAxis(String url) {
if (_activeAxisUrl == url) return;
_activeAxisUrl = url;
_axisGeneration++;
_clearSprites();
}
Future<SpriteThumbnailAxis> _loadAxis(String url) {
final cached = _readAxis(url);
if (cached != null) return Future.value(cached);
@@ -239,7 +234,6 @@ class SpriteThumbnailAxisService extends ChangeNotifier
} on SpriteThumbnailForbiddenException {
if (_disposed) return SpriteThumbnailAxis.empty(url);
_axisCache.remove(url);
if (_activeAxisUrl == url) _clearSprites();
} catch (_) {
break;
}
@@ -274,6 +268,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
if (current == null) return const [];
final index = axis.cues.indexOf(current);
final candidates = <SpriteThumbnailCue>[current];
if (spriteCacheCapacity <= 1) return candidates;
for (final direction in const [1, -1]) {
for (var step = 1; step < axis.cues.length; step++) {
final neighborIndex = index + direction * step;
@@ -293,23 +288,23 @@ class SpriteThumbnailAxisService extends ChangeNotifier
SpriteThumbnailAxis axis,
SpriteThumbnailCue cue,
) {
final cached = _readSprite(cue.spriteFile);
final spriteUrl = axis.resolveSpriteUri(cue.spriteFile).toString();
final cached = _readSprite(spriteUrl);
if (cached != null) return Future.value(cached);
if (_failedSprites.contains(cue.spriteFile)) return Future.value();
final existing = _spriteRequests[cue.spriteFile];
if (_failedSprites.contains(spriteUrl)) return Future.value();
final existing = _spriteRequests[spriteUrl];
if (existing != null) return existing;
final generation = _axisGeneration;
final request = _loadSprite(axis, cue, generation);
_spriteRequests[cue.spriteFile] = request;
final request = _loadSprite(axis, cue, spriteUrl);
_spriteRequests[spriteUrl] = request;
return request.whenComplete(() {
_spriteRequests.remove(cue.spriteFile);
_spriteRequests.remove(spriteUrl);
});
}
Future<_CachedSprite?> _loadSprite(
SpriteThumbnailAxis axis,
SpriteThumbnailCue cue,
int generation,
String spriteUrl,
) async {
SpriteThumbnailDecodedImage? decoded;
try {
@@ -318,16 +313,16 @@ class SpriteThumbnailAxisService extends ChangeNotifier
decoded = null;
}
if (decoded == null) {
_failedSprites.add(cue.spriteFile);
_failedSprites.add(spriteUrl);
if (!_disposed) notifyListeners();
return null;
}
if (_disposed || generation != _axisGeneration) {
if (_disposed) {
decoded.image.dispose();
return null;
}
final cached = _CachedSprite(decoded);
_putSprite(cue.spriteFile, cached);
_putSprite(spriteUrl, cached);
notifyListeners();
return cached;
}
@@ -342,7 +337,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
void _putSprite(String key, _CachedSprite value) {
_spriteCache.remove(key)?.decoded.image.dispose();
_spriteCache[key] = value;
while (_spriteCache.length > spriteImageCacheCapacity) {
while (_spriteCache.length > spriteCacheCapacity) {
final oldest = _spriteCache.remove(_spriteCache.keys.first);
oldest?.decoded.image.dispose();
}
@@ -378,8 +373,6 @@ class SpriteThumbnailAxisService extends ChangeNotifier
}
void _clearAll() {
_axisGeneration++;
_activeAxisUrl = null;
_axisCache.clear();
_axisRequests.clear();
_clearSprites();
@@ -38,6 +38,7 @@ class WatchRecordsController extends ChangeNotifier {
String? error;
String? loadMoreError;
String? actionError;
int? lastErrorCode;
int _pageIndex = 0;
int _requestSeq = 0;
bool _disposed = false;
@@ -50,6 +51,7 @@ class WatchRecordsController extends ChangeNotifier {
error = null;
loadMoreError = null;
actionError = null;
lastErrorCode = null;
_notify();
try {
final page = await _history.recent(pageIndex: 1, pageSize: pageSize);
@@ -71,6 +73,7 @@ class WatchRecordsController extends ChangeNotifier {
);
if (!_disposed && request == _requestSeq) {
error = failure is ApiException ? failure.message : 'progressError';
if (failure is ApiException) lastErrorCode = failure.code;
}
} finally {
if (!_disposed && request == _requestSeq) {
@@ -86,6 +89,7 @@ class WatchRecordsController extends ChangeNotifier {
final request = ++_requestSeq;
loadingMore = true;
loadMoreError = null;
lastErrorCode = null;
_notify();
try {
final page = await _history.recent(
@@ -108,6 +112,7 @@ class WatchRecordsController extends ChangeNotifier {
loadMoreError = failure is ApiException
? failure.message
: 'progressError';
if (failure is ApiException) lastErrorCode = failure.code;
}
} finally {
if (!_disposed && request == _requestSeq) {
@@ -148,17 +153,19 @@ class WatchRecordsController extends ChangeNotifier {
total = total > 0 ? total - 1 : 0;
hasMore = records.length < total;
actionError = null;
lastErrorCode = null;
_notify();
try {
await _history.remove(dramaId);
return true;
} catch (_) {
} catch (failure) {
final next = [...records];
next.insert(index > next.length ? next.length : index, removed);
records = next;
total += 1;
hasMore = records.length < total;
actionError = 'recordDeleteFailed';
if (failure is ApiException) lastErrorCode = failure.code;
return false;
} finally {
_notify();
@@ -179,16 +186,18 @@ class WatchRecordsController extends ChangeNotifier {
loadingMore = false;
clearing = true;
actionError = null;
lastErrorCode = null;
_notify();
try {
await _history.clear();
return true;
} catch (_) {
} catch (failure) {
records = previous;
total = previousTotal;
_pageIndex = previousPageIndex;
hasMore = records.length < total;
actionError = 'recordClearFailed';
if (failure is ApiException) lastErrorCode = failure.code;
return false;
} finally {
clearing = false;
@@ -305,6 +314,23 @@ class WatchRecordsController extends ChangeNotifier {
if (!_disposed) notifyListeners();
}
/// 切换账号/设备身份时清除内存数据,不删除服务端记录。
void reset() {
_requestSeq += 1;
records = const [];
total = 0;
loading = false;
loadingMore = false;
hasMore = false;
clearing = false;
error = null;
loadMoreError = null;
actionError = null;
lastErrorCode = null;
_pageIndex = 0;
_notify();
}
@override
void dispose() {
_disposed = true;
+239
View File
@@ -0,0 +1,239 @@
// Author: fruit.com.cn
/// 账号资料页只读字段的展示格式化。
///
/// 后端存的是 ISO 国家码、BCP-47 语言标签和 IANA 时区(`ID` / `id-ID` / `Asia/Jakarta`),
/// 直接展示对用户没有意义,这里统一转成当前界面语言的名称。
/// 国家与城市名只维护中文与英文两套:界面语言为印尼语时回退英文名,
/// 语言名与账号状态则三种界面语言都有。
library;
const _countryNamesZh = {
'ID': '印度尼西亚',
'MY': '马来西亚',
'SG': '新加坡',
'TH': '泰国',
'VN': '越南',
'PH': '菲律宾',
'KH': '柬埔寨',
'MM': '缅甸',
'LA': '老挝',
'BN': '文莱',
'CN': '中国',
'TW': '中国台湾',
'HK': '中国香港',
'MO': '中国澳门',
'JP': '日本',
'KR': '韩国',
'IN': '印度',
'PK': '巴基斯坦',
'BD': '孟加拉国',
'LK': '斯里兰卡',
'NP': '尼泊尔',
'US': '美国',
'CA': '加拿大',
'MX': '墨西哥',
'BR': '巴西',
'AR': '阿根廷',
'CL': '智利',
'CO': '哥伦比亚',
'PE': '秘鲁',
'VE': '委内瑞拉',
'EC': '厄瓜多尔',
'GT': '危地马拉',
'DO': '多米尼加',
'GB': '英国',
'DE': '德国',
'FR': '法国',
'ES': '西班牙',
'IT': '意大利',
'NL': '荷兰',
'PL': '波兰',
'RU': '俄罗斯',
'UA': '乌克兰',
'TR': '土耳其',
'SA': '沙特阿拉伯',
'AE': '阿联酋',
'IL': '以色列',
'EG': '埃及',
'NG': '尼日利亚',
'ZA': '南非',
'KE': '肯尼亚',
'MA': '摩洛哥',
'AU': '澳大利亚',
'NZ': '新西兰',
};
const _countryNamesEn = {
'ID': 'Indonesia',
'MY': 'Malaysia',
'SG': 'Singapore',
'TH': 'Thailand',
'VN': 'Vietnam',
'PH': 'Philippines',
'KH': 'Cambodia',
'MM': 'Myanmar',
'LA': 'Laos',
'BN': 'Brunei',
'CN': 'China',
'TW': 'Taiwan',
'HK': 'Hong Kong',
'MO': 'Macau',
'JP': 'Japan',
'KR': 'South Korea',
'IN': 'India',
'PK': 'Pakistan',
'BD': 'Bangladesh',
'LK': 'Sri Lanka',
'NP': 'Nepal',
'US': 'United States',
'CA': 'Canada',
'MX': 'Mexico',
'BR': 'Brazil',
'AR': 'Argentina',
'CL': 'Chile',
'CO': 'Colombia',
'PE': 'Peru',
'VE': 'Venezuela',
'EC': 'Ecuador',
'GT': 'Guatemala',
'DO': 'Dominican Republic',
'GB': 'United Kingdom',
'DE': 'Germany',
'FR': 'France',
'ES': 'Spain',
'IT': 'Italy',
'NL': 'Netherlands',
'PL': 'Poland',
'RU': 'Russia',
'UA': 'Ukraine',
'TR': 'Turkey',
'SA': 'Saudi Arabia',
'AE': 'United Arab Emirates',
'IL': 'Israel',
'EG': 'Egypt',
'NG': 'Nigeria',
'ZA': 'South Africa',
'KE': 'Kenya',
'MA': 'Morocco',
'AU': 'Australia',
'NZ': 'New Zealand',
};
const _timezoneNamesZh = {
'Asia/Jakarta': '雅加达',
'Asia/Kuala_Lumpur': '吉隆坡',
'Asia/Singapore': '新加坡',
'Asia/Bangkok': '曼谷',
'Asia/Ho_Chi_Minh': '胡志明市',
'Asia/Manila': '马尼拉',
'Asia/Phnom_Penh': '金边',
'Asia/Yangon': '仰光',
'Asia/Vientiane': '万象',
'Asia/Brunei': '斯里巴加湾市',
'Asia/Shanghai': '上海',
'Asia/Taipei': '台北',
'Asia/Hong_Kong': '香港',
'Asia/Macau': '澳门',
'Asia/Tokyo': '东京',
'Asia/Seoul': '首尔',
'Asia/Kolkata': '加尔各答',
'Asia/Karachi': '卡拉奇',
'Asia/Dhaka': '达卡',
'Asia/Colombo': '科伦坡',
'Asia/Kathmandu': '加德满都',
'America/New_York': '纽约',
'America/Toronto': '多伦多',
'America/Mexico_City': '墨西哥城',
'America/Sao_Paulo': '圣保罗',
'America/Argentina/Buenos_Aires': '布宜诺斯艾利斯',
'America/Santiago': '圣地亚哥',
'America/Bogota': '波哥大',
'America/Lima': '利马',
'America/Caracas': '加拉加斯',
'America/Guayaquil': '瓜亚基尔',
'America/Guatemala': '危地马拉城',
'America/Santo_Domingo': '圣多明各',
'Europe/London': '伦敦',
'Europe/Berlin': '柏林',
'Europe/Paris': '巴黎',
'Europe/Madrid': '马德里',
'Europe/Rome': '罗马',
'Europe/Amsterdam': '阿姆斯特丹',
'Europe/Warsaw': '华沙',
'Europe/Moscow': '莫斯科',
'Europe/Kyiv': '基辅',
'Europe/Istanbul': '伊斯坦布尔',
'Asia/Riyadh': '利雅得',
'Asia/Dubai': '迪拜',
'Asia/Jerusalem': '耶路撒冷',
'Africa/Cairo': '开罗',
'Africa/Lagos': '拉各斯',
'Africa/Johannesburg': '约翰内斯堡',
'Africa/Nairobi': '内罗毕',
'Africa/Casablanca': '卡萨布兰卡',
'Australia/Sydney': '悉尼',
'Pacific/Auckland': '奥克兰',
};
const _languageNames = {
'id': {'zh': '印度尼西亚语', 'en': 'Indonesian', 'id': 'Bahasa Indonesia'},
'en': {'zh': '英语', 'en': 'English', 'id': 'Inggris'},
'zh': {'zh': '中文', 'en': 'Chinese', 'id': 'Mandarin'},
};
const _statusNames = {
'normal': {'zh': '正常', 'en': 'Active', 'id': 'Aktif'},
'limited': {'zh': '受限', 'en': 'Limited', 'id': 'Dibatasi'},
'banned': {'zh': '已封禁', 'en': 'Banned', 'id': 'Diblokir'},
'deactivated': {'zh': '已注销', 'en': 'Deactivated', 'id': 'Dinonaktifkan'},
};
String _pick(Map<String, String> names, String localeName) =>
names[localeName] ?? names['en']!;
/// 国家码 → 国家名;未收录的码原样返回。
String countryName(String code, String localeName) {
final key = code.trim().toUpperCase();
if (key.isEmpty) return '';
final names = localeName == 'zh' ? _countryNamesZh : _countryNamesEn;
return names[key] ?? key;
}
/// IANA 时区 → 城市名;中文界面查表,其余语言取时区里的城市段。
String timezoneName(String timezone, String localeName) {
final value = timezone.trim();
if (value.isEmpty) return '';
if (localeName == 'zh') {
final name = _timezoneNamesZh[value];
if (name != null) return name;
}
final city = value.split('/').last.replaceAll('_', ' ');
return city.isEmpty ? value : city;
}
/// BCP-47 语言标签 → 语言名,按主语言归类(`zh-TW` 也算中文)。
String languageName(String language, String localeName) {
final value = language.trim();
if (value.isEmpty) return '';
final primary = value.split(RegExp('[-_]')).first.toLowerCase();
final names = _languageNames[primary];
return names == null ? value : _pick(names, localeName);
}
/// 账号状态 → 展示文案;未知状态原样返回。
String accountStatusText(String status, String localeName) {
final value = status.trim().toLowerCase();
final names = _statusNames[value];
return names == null ? status : _pick(names, localeName);
}
/// VIP 等级:0 表示未开通,避免用户看到一个孤零零的 0。
String vipLevelText(int level, String localeName) {
if (level > 0) return 'VIP $level';
return switch (localeName) {
'zh' => '未开通',
'id' => 'Belum aktif',
_ => 'Not subscribed',
};
}
+12 -10
View File
@@ -4,14 +4,16 @@ import 'package:flutter/widgets.dart';
/// 无位移的短促淡入转场。
class FadePageRoute<T> extends PageRouteBuilder<T> {
FadePageRoute({required WidgetBuilder builder, super.settings})
: super(
transitionDuration: const Duration(milliseconds: 220),
reverseTransitionDuration: const Duration(milliseconds: 180),
pageBuilder: (context, _, _) => builder(context),
transitionsBuilder: (context, animation, _, child) => FadeTransition(
opacity: CurvedAnimation(parent: animation, curve: Curves.easeOut),
child: child,
),
);
FadePageRoute({
required WidgetBuilder builder,
super.settings,
super.transitionDuration = const Duration(milliseconds: 220),
super.reverseTransitionDuration = const Duration(milliseconds: 180),
}) : super(
pageBuilder: (context, _, _) => builder(context),
transitionsBuilder: (context, animation, _, child) => FadeTransition(
opacity: CurvedAnimation(parent: animation, curve: Curves.easeOut),
child: child,
),
);
}
+11 -5
View File
@@ -78,7 +78,12 @@ abstract final class AppColors {
/// 中性深灰卡片与控件表面。
static const contentCard = Color(0xFF16161A);
static const contentSurface = Color(0xFF1C1C1E);
static const skeletonSurface = Color(0xFF141414);
/// 首页、分类与搜索网格骨架的极暗底色。
static const skeletonSurface = Color(0xFF0E0E0E);
/// 播放器、推荐与详情页大面积媒体占位的深灰底色。
static const skeletonMedia = Color(0xFF1C1C1E);
static const contentChip = Color(0xFF2C2C2E);
static const contentBorder = Color(0x1AFFFFFF);
static const filterChipSelected = Color(0xFF21090E);
@@ -128,9 +133,10 @@ abstract final class AppColors {
/// 底部导航底色。
static const bar = ink;
/// 底部导航专用:纯黑背景、选中白与未选中灰。
/// 底部导航专用:纯黑背景、选中品牌红与未选中白。
static const navBackground = Color(0xFF000000);
static const navSelected = Color(0xFFFFFFFF);
static const brandRed = Color(0xFFF04E4E);
static const navSelected = brandRed;
/// 卡片阴影(深色几乎不用阴影)。
static const cardShadow = Color(0x00000000);
@@ -183,8 +189,8 @@ abstract final class AppColors {
/// 封面集数胶囊。
static const badgeBeige = raised;
/// 导航未选中。
static const navUnselected = textSecondary;
/// 导航未选中(设计稿为白色线框 + 白色文字)。
static const navUnselected = Color(0xFFFFFFFF);
/// 首页内容角标。
static const badgeHot = Color(0xFFE5484D);
+1 -1
View File
@@ -229,7 +229,7 @@ abstract final class AppDimens {
static const double mineSectionLinkFont = 12;
static const double mineSectionGap = 20;
static const double mineContinueCardWidth = 96;
static const double mineContinueRowHeight = 168;
static const double mineContinueRowHeight = 172;
static const double mineContinueTitleFont = 13;
static const double mineContinueMetaFont = 11;
static const double mineStatsValueFont = 18;
+6 -14
View File
@@ -7,18 +7,12 @@ import 'app_bottom_nav.dart';
/// 客户端根导航的固定顺序。
enum AppRootTab {
home(
assetPath: 'assets/icon/film_reel.png',
selectedAssetPath: 'assets/icon/film_reel_filled.png',
),
home(),
recommend(),
following(),
mine();
const AppRootTab({this.assetPath, this.selectedAssetPath});
final String? assetPath;
final String? selectedAssetPath;
const AppRootTab();
}
extension AppRootTabUi on AppRootTab {
@@ -30,15 +24,15 @@ extension AppRootTabUi on AppRootTab {
};
IconData get icon => switch (this) {
AppRootTab.home => Icons.theaters_outlined,
AppRootTab.recommend => Icons.smart_display_outlined,
AppRootTab.home => Icons.home_outlined,
AppRootTab.recommend => Icons.celebration_outlined,
AppRootTab.following => Icons.bookmark_border_rounded,
AppRootTab.mine => Icons.person_outline_rounded,
};
IconData get selectedIcon => switch (this) {
AppRootTab.home => Icons.theaters,
AppRootTab.recommend => Icons.smart_display_rounded,
AppRootTab.home => Icons.home_rounded,
AppRootTab.recommend => Icons.celebration_rounded,
AppRootTab.following => Icons.bookmark_rounded,
AppRootTab.mine => Icons.person_rounded,
};
@@ -75,8 +69,6 @@ class AppRootBottomNav extends StatelessWidget {
tabKey: tab.tabKey,
icon: tab.icon,
selectedIcon: tab.selectedIcon,
assetPath: tab.assetPath,
selectedAssetPath: tab.selectedAssetPath,
label: tab.label(l10n),
selected: tab == selected,
onTap: () => onSelected(tab),
+2 -1
View File
@@ -15,7 +15,7 @@ Future<void> openAuthPage(BuildContext context, {bool signUpMode = false}) {
/// 受限动作的登录闸:已登录返回 true;未登录弹底部提示并引导登录,返回 false。
///
/// 首页/发现/详情保持匿名可看,只有收藏、点赞、评论这类"要对到具体账号"的动作才走这里。
/// 首页/发现/详情与非付费互动保持匿名可用;解锁、权益与消耗类动作走这里。
Future<bool> ensureSignedIn(BuildContext context) async {
final auth = context.read<AuthController>();
if (auth.isSignedIn) return true;
@@ -76,6 +76,7 @@ Future<bool> ensureSignedIn(BuildContext context) async {
if (go == true && context.mounted) {
await openAuthPage(context);
if (context.mounted) return context.read<AuthController>().isSignedIn;
}
return false;
}
+47 -34
View File
@@ -11,7 +11,8 @@ const Duration _shimmerPeriod = Duration(milliseconds: 1400);
const double _shimmerTravel = 2.4;
const double _shimmerStart = -1.2;
const double _subtitleWidthFactor = 0.62;
const Color _shimmerHighlight = Color(0x38FFFFFF);
const double _shimmerPhaseStep = 0.13;
const Color _shimmerHighlight = Color(0x0DFFFFFF);
/// 首页短剧网格的占位。行数至少铺满可视高度,并带一道扫光。
class DramaGridSkeleton extends StatefulWidget {
@@ -53,21 +54,19 @@ class _DramaGridSkeletonState extends State<DramaGridSkeleton>
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final grid = _grid(constraints.maxWidth, constraints.maxHeight);
return AnimatedBuilder(
animation: _shimmer,
builder: (context, child) => ShaderMask(
blendMode: BlendMode.srcATop,
shaderCallback: (bounds) => _shader(bounds),
child: child,
builder: (context, _) => _grid(
constraints.maxWidth,
constraints.maxHeight,
_shimmer.value,
),
child: grid,
);
},
);
}
Widget _grid(double width, double height) {
Widget _grid(double width, double height, double shimmerValue) {
final itemWidth = _itemWidth(width);
final itemExtent = _itemExtent(itemWidth);
return GridView.builder(
@@ -85,7 +84,8 @@ class _DramaGridSkeletonState extends State<DramaGridSkeleton>
mainAxisExtent: itemExtent,
),
itemCount: _fillCount(height, itemExtent),
itemBuilder: (context, index) => _SkeletonCard(index: index),
itemBuilder: (context, index) =>
_SkeletonCard(index: index, shimmerValue: shimmerValue),
);
}
@@ -105,48 +105,61 @@ class _DramaGridSkeletonState extends State<DramaGridSkeleton>
final rows = (height / rowHeight).ceil() + 1;
return math.max(widget.itemCount, rows * widget.columns);
}
Shader _shader(Rect bounds) {
final shift = _shimmerStart + _shimmerTravel * _shimmer.value;
return LinearGradient(
begin: Alignment(shift, -0.3),
end: Alignment(shift + 1, 0.3),
colors: const [
AppColors.skeletonSurface,
_shimmerHighlight,
AppColors.skeletonSurface,
],
).createShader(bounds);
}
}
class _SkeletonCard extends StatelessWidget {
const _SkeletonCard({required this.index});
const _SkeletonCard({required this.index, required this.shimmerValue});
final int index;
final double shimmerValue;
@override
Widget build(BuildContext context) {
return Column(
final phase = (shimmerValue + index * _shimmerPhaseStep) % 1.0;
return Stack(
key: Key('drama-grid-skeleton-$index'),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AspectRatio(
aspectRatio: AppDimens.cardCoverAspectRatio,
child: const _SkeletonBlock(),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AspectRatio(
aspectRatio: AppDimens.cardCoverAspectRatio,
child: const _SkeletonBlock(),
),
const SizedBox(height: AppDimens.cardCoverTitleGap),
const _SkeletonBar(),
const SizedBox(height: AppDimens.skeletonTitleBarGap),
const FractionallySizedBox(
widthFactor: _subtitleWidthFactor,
child: _SkeletonBar(),
),
],
),
const SizedBox(height: AppDimens.cardCoverTitleGap),
const _SkeletonBar(),
const SizedBox(height: AppDimens.skeletonTitleBarGap),
const FractionallySizedBox(
widthFactor: _subtitleWidthFactor,
child: _SkeletonBar(),
Positioned.fill(
child: IgnorePointer(
child: ClipRRect(
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
child: DecoratedBox(
decoration: BoxDecoration(gradient: _cardHighlight(phase)),
),
),
),
),
],
);
}
}
LinearGradient _cardHighlight(double shimmerValue) {
final shift = _shimmerStart + _shimmerTravel * shimmerValue;
return LinearGradient(
begin: Alignment(shift, -0.3),
end: Alignment(shift + 1, 0.3),
colors: const [Colors.transparent, _shimmerHighlight, Colors.transparent],
stops: const [0.42, 0.5, 0.58],
);
}
class _SkeletonBlock extends StatelessWidget {
const _SkeletonBlock();
+65 -10
View File
@@ -5,6 +5,24 @@ import 'package:flutter/material.dart';
import '../config/app_config.dart';
import '../theme/app_colors.dart';
const int _minImageDecodePixels = 96;
const int _maxImageDecodePixels = 2048;
/// 将布局逻辑尺寸换算成有限像素尺寸,兼顾小头像和全屏首帧。
int resolveImageDecodePixels(double? logicalExtent, double devicePixelRatio) {
final ratio = devicePixelRatio.isFinite && devicePixelRatio > 0
? devicePixelRatio
: 1.0;
final extent =
logicalExtent != null && logicalExtent.isFinite && logicalExtent > 0
? logicalExtent
: 120.0;
return (extent * ratio)
.ceil()
.clamp(_minImageDecodePixels, _maxImageDecodePixels)
.toInt();
}
/// 封面图统一入口:后端给的是相对路径,这里补服务地址并处理加载失败。
class RemoteImage extends StatelessWidget {
const RemoteImage(
@@ -17,6 +35,8 @@ class RemoteImage extends StatelessWidget {
this.fallbackIconKey,
this.fallbackAspectRatio,
this.fallbackColor = AppColors.raised,
this.decodeWidth,
this.decodeHeight,
});
final String path;
@@ -27,21 +47,56 @@ class RemoteImage extends StatelessWidget {
final Key? fallbackIconKey;
final double? fallbackAspectRatio;
final Color fallbackColor;
final int? decodeWidth;
final int? decodeHeight;
@override
Widget build(BuildContext context) {
final url = AppConfig.mediaUrl(path);
if (url.isEmpty) return _fallback(brand: showFallbackIcon);
return Image.network(
url,
width: width,
height: height,
fit: fit,
gaplessPlayback: true,
errorBuilder: (_, _, _) => _fallback(brand: showFallbackIcon),
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded || frame != null) return child;
return _fallback(brand: showFallbackIcon);
return LayoutBuilder(
builder: (context, constraints) {
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
final layoutWidth = constraints.hasBoundedWidth
? constraints.maxWidth
: width;
final aspectRatio =
fallbackAspectRatio != null &&
fallbackAspectRatio!.isFinite &&
fallbackAspectRatio! > 0
? fallbackAspectRatio
: null;
final inferredHeight = constraints.hasBoundedHeight
? constraints.maxHeight
: height ??
(layoutWidth != null && aspectRatio != null
? layoutWidth / aspectRatio
: null);
final cacheWidth =
decodeWidth ?? resolveImageDecodePixels(layoutWidth, pixelRatio);
final cacheHeight =
decodeHeight ??
(inferredHeight == null
? null
: resolveImageDecodePixels(inferredHeight, pixelRatio));
return Image.network(
url,
width: width,
height: height,
fit: fit,
cacheWidth: cacheWidth
.clamp(_minImageDecodePixels, _maxImageDecodePixels)
.toInt(),
cacheHeight: cacheHeight
?.clamp(_minImageDecodePixels, _maxImageDecodePixels)
.toInt(),
gaplessPlayback: true,
errorBuilder: (_, _, _) => _fallback(brand: showFallbackIcon),
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded || frame != null) return child;
return _fallback(brand: showFallbackIcon);
},
);
},
);
}
+25 -1
View File
@@ -55,12 +55,24 @@
"viewers": {"type": "String"}
}
},
"watchFullSeries": "Watch full series · {episodes} eps",
"watchFullSeries": "Watch full series {episodes} eps",
"@watchFullSeries": {
"placeholders": {
"episodes": {"type": "String"}
}
},
"feedEpisodePrefix": "EP{episode} | ",
"@feedEpisodePrefix": {
"placeholders": {
"episode": {"type": "int"}
}
},
"feedWatchingCount": "{count} watching",
"@feedWatchingCount": {
"placeholders": {
"count": {"type": "String"}
}
},
"feedTabAnime": "Anime",
"feedTabReal": "Live-action",
"feedTabForYou": "For you",
@@ -265,6 +277,18 @@
"pictureInPicture": "Picture in picture",
"pipUnavailable": "Picture in picture is unavailable on this device",
"originalTag": "Original",
"originalProduction": "Original",
"watchNowAction": "Watch Now",
"newArrivalBadge": "NEW",
"editorPick": "Editor's Pick",
"totalEpisodesShort": "{count} eps",
"@totalEpisodesShort": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"dramaTag": "Short drama",
"episodeLabel": "Episode {number}",
"@episodeLabel": {
+30 -1
View File
@@ -49,7 +49,24 @@
"hotBadge": "Hits",
"filterAll": "Semua",
"seriesMeta": "Serial · {episodes} eps | {viewers} menonton",
"watchFullSeries": "Tonton serial lengkap · {episodes} eps",
"watchFullSeries": "Tonton serial lengkap {episodes} eps",
"@watchFullSeries": {
"placeholders": {
"episodes": {"type": "String"}
}
},
"feedEpisodePrefix": "EP{episode} | ",
"@feedEpisodePrefix": {
"placeholders": {
"episode": {"type": "int"}
}
},
"feedWatchingCount": "{count} menonton",
"@feedWatchingCount": {
"placeholders": {
"count": {"type": "String"}
}
},
"feedTabAnime": "Anime",
"feedTabReal": "Live-action",
"feedTabForYou": "Untukmu",
@@ -239,6 +256,18 @@
"pictureInPicture": "Gambar dalam gambar",
"pipUnavailable": "Gambar dalam gambar tidak tersedia di perangkat ini",
"originalTag": "Original",
"originalProduction": "Original",
"watchNowAction": "Tonton Sekarang",
"newArrivalBadge": "BARU",
"editorPick": "Pilihan Editor",
"totalEpisodesShort": "{count} eps",
"@totalEpisodesShort": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"dramaTag": "Drama pendek",
"episodeLabel": "Episode {number}",
"@episodeLabel": {
+43 -1
View File
@@ -397,9 +397,21 @@ abstract class AppLocalizations {
/// No description provided for @watchFullSeries.
///
/// In en, this message translates to:
/// **'Watch full series · {episodes} eps'**
/// **'Watch full series {episodes} eps'**
String watchFullSeries(String episodes);
/// No description provided for @feedEpisodePrefix.
///
/// In en, this message translates to:
/// **'EP{episode} | '**
String feedEpisodePrefix(int episode);
/// No description provided for @feedWatchingCount.
///
/// In en, this message translates to:
/// **'{count} watching'**
String feedWatchingCount(String count);
/// No description provided for @feedTabAnime.
///
/// In en, this message translates to:
@@ -1198,6 +1210,36 @@ abstract class AppLocalizations {
/// **'Original'**
String get originalTag;
/// No description provided for @originalProduction.
///
/// In en, this message translates to:
/// **'Original'**
String get originalProduction;
/// No description provided for @watchNowAction.
///
/// In en, this message translates to:
/// **'Watch Now'**
String get watchNowAction;
/// No description provided for @newArrivalBadge.
///
/// In en, this message translates to:
/// **'NEW'**
String get newArrivalBadge;
/// No description provided for @editorPick.
///
/// In en, this message translates to:
/// **'Editor\'s Pick'**
String get editorPick;
/// No description provided for @totalEpisodesShort.
///
/// In en, this message translates to:
/// **'{count} eps'**
String totalEpisodesShort(int count);
/// No description provided for @dramaTag.
///
/// In en, this message translates to:
+28 -1
View File
@@ -162,7 +162,17 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String watchFullSeries(String episodes) {
return 'Watch full series · $episodes eps';
return 'Watch full series $episodes eps';
}
@override
String feedEpisodePrefix(int episode) {
return 'EP$episode | ';
}
@override
String feedWatchingCount(String count) {
return '$count watching';
}
@override
@@ -594,6 +604,23 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get originalTag => 'Original';
@override
String get originalProduction => 'Original';
@override
String get watchNowAction => 'Watch Now';
@override
String get newArrivalBadge => 'NEW';
@override
String get editorPick => 'Editor\'s Pick';
@override
String totalEpisodesShort(int count) {
return '$count eps';
}
@override
String get dramaTag => 'Short drama';
+28 -1
View File
@@ -162,7 +162,17 @@ class AppLocalizationsId extends AppLocalizations {
@override
String watchFullSeries(String episodes) {
return 'Tonton serial lengkap · $episodes eps';
return 'Tonton serial lengkap $episodes eps';
}
@override
String feedEpisodePrefix(int episode) {
return 'EP$episode | ';
}
@override
String feedWatchingCount(String count) {
return '$count menonton';
}
@override
@@ -595,6 +605,23 @@ class AppLocalizationsId extends AppLocalizations {
@override
String get originalTag => 'Original';
@override
String get originalProduction => 'Original';
@override
String get watchNowAction => 'Tonton Sekarang';
@override
String get newArrivalBadge => 'BARU';
@override
String get editorPick => 'Pilihan Editor';
@override
String totalEpisodesShort(int count) {
return '$count eps';
}
@override
String get dramaTag => 'Drama pendek';
+28 -1
View File
@@ -159,7 +159,17 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String watchFullSeries(String episodes) {
return '观看完整剧集 · 全$episodes集';
return '观看完整剧集 全$episodes集';
}
@override
String feedEpisodePrefix(int episode) {
return '第$episode集|';
}
@override
String feedWatchingCount(String count) {
return '共$count人在看';
}
@override
@@ -587,6 +597,23 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get originalTag => '原创';
@override
String get originalProduction => '原创出品';
@override
String get watchNowAction => '立即观看';
@override
String get newArrivalBadge => '上新';
@override
String get editorPick => '编辑精选';
@override
String totalEpisodesShort(int count) {
return '全$count集';
}
@override
String get dramaTag => '短剧';
+30 -1
View File
@@ -49,7 +49,24 @@
"hotBadge": "爆剧",
"filterAll": "全部",
"seriesMeta": "系列剧 · 共{episodes}集 | 共{viewers}人在追",
"watchFullSeries": "观看完整剧集 · 全{episodes}集",
"watchFullSeries": "观看完整剧集 全{episodes}集",
"@watchFullSeries": {
"placeholders": {
"episodes": {"type": "String"}
}
},
"feedEpisodePrefix": "第{episode}集|",
"@feedEpisodePrefix": {
"placeholders": {
"episode": {"type": "int"}
}
},
"feedWatchingCount": "共{count}人在看",
"@feedWatchingCount": {
"placeholders": {
"count": {"type": "String"}
}
},
"feedTabAnime": "漫剧",
"feedTabReal": "真人剧",
"feedTabForYou": "推荐",
@@ -239,6 +256,18 @@
"pictureInPicture": "画中画",
"pipUnavailable": "此设备无法使用画中画",
"originalTag": "原创",
"originalProduction": "原创出品",
"watchNowAction": "立即观看",
"newArrivalBadge": "上新",
"editorPick": "编辑精选",
"totalEpisodesShort": "全{count}集",
"@totalEpisodesShort": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"dramaTag": "短剧",
"episodeLabel": "第 {number} 集",
"@episodeLabel": {
+30 -7
View File
@@ -8,6 +8,7 @@ import 'package:provider/provider.dart';
import '../../core/data/models/account_profile.dart';
import '../../core/data/repositories/account_repository.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/formatting/account_display.dart';
import '../../core/formatting/error_text.dart';
import '../../core/formatting/localized_date_time.dart';
import '../../core/theme/app_colors.dart';
@@ -225,6 +226,7 @@ class _AccountProfilePageState extends State<AccountProfilePage> {
);
Widget _readOnlyCard(AccountProfile profile, AppLocalizations l10n) {
final localeName = Localizations.localeOf(context).languageCode;
return _AccountCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -238,13 +240,34 @@ class _AccountProfilePageState extends State<AccountProfilePage> {
),
const SizedBox(height: 10),
_info(l10n.accountMaskedAccount, profile.maskedTarget),
_info(l10n.accountCountry, profile.countryCode),
_info(
l10n.accountCountry,
countryName(profile.countryCode, localeName),
),
_info(l10n.accountCurrency, profile.currency),
_info(l10n.accountStatus, profile.status),
_info(l10n.accountLanguage, profile.language),
_info(l10n.accountTimezone, profile.timezone),
_info(l10n.accountRegion, profile.regionCode),
_info(l10n.accountVipLevel, '${profile.vipLevel}'),
_info(
l10n.accountStatus,
accountStatusText(profile.status, localeName),
),
_info(
l10n.accountLanguage,
languageName(profile.language, localeName),
),
_info(
l10n.accountTimezone,
timezoneName(profile.timezone, localeName),
),
// region 与 country 后端写的是同一个值,重复时不再单列一行
if (profile.regionCode.isNotEmpty &&
profile.regionCode != profile.countryCode)
_info(
l10n.accountRegion,
countryName(profile.regionCode, localeName),
),
_info(
l10n.accountVipLevel,
vipLevelText(profile.vipLevel, localeName),
),
if (profile.createdAt != null)
_info(
l10n.accountCreatedAt,
@@ -275,7 +298,7 @@ class _AccountProfilePageState extends State<AccountProfilePage> {
),
Flexible(
child: Text(
value.isEmpty ? '-' : value,
value.isEmpty ? '—' : value,
textAlign: TextAlign.right,
style: const TextStyle(fontSize: AppDimens.body),
),
-1
View File
@@ -8,7 +8,6 @@ import 'package:provider/provider.dart';
import '../../core/data/remote/api_client.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/formatting/error_text.dart';
import '../../core/platform/haptics.dart';
import '../../core/platform/keyboard_inset.dart';
import '../../core/theme/app_colors.dart';
+6 -18
View File
@@ -38,7 +38,6 @@ class DramaDetailLogic extends ChangeNotifier {
int? continueIndex;
WatchProgress? progress;
String? progressError;
int _favoriteCountDelta = 0;
bool _disposed = false;
void notify() {
@@ -47,6 +46,7 @@ class DramaDetailLogic extends ChangeNotifier {
/// 列表卡片只带一集可播预览,进详情时补一次完整剧集列表。
Future<void> load(Future<Drama> Function() fetch) async {
favorites.applyServerCount(drama.id, drama.favoriteCount, notify: false);
if (drama.detailLoaded) {
await loadContinue();
return;
@@ -57,6 +57,7 @@ class DramaDetailLogic extends ChangeNotifier {
notify();
try {
drama = await fetch();
favorites.applyServerCount(drama.id, drama.favoriteCount);
await loadContinue();
} on ApiException catch (exception) {
failed = true;
@@ -139,25 +140,12 @@ class DramaDetailLogic extends ChangeNotifier {
await loadContinue();
}
/// 详情页展示用的收藏数;没有服务端计数时继续保持缺省展示。
int? get adjustedFavoriteCount {
final base = drama.favoriteCount;
if (base == null) return null;
final adjusted = base + _favoriteCountDelta;
return adjusted < 0 ? 0 : adjusted;
}
/// 详情页展示用的收藏数,统一从全局 FavoriteController 读取。
int? get adjustedFavoriteCount => favorites.favoriteCountFor(drama);
/// 收藏切换:乐观状态由控制器负责回滚,这里只在成功后同步计数。
/// 收藏切换:状态与计数均由全局控制器维护。
Future<bool> toggleFavorite() async {
final wasSaved = favorites.isSaved(drama.id);
final ok = await favorites.toggle(drama.id, card: drama);
if (!ok) return false;
final nowSaved = favorites.isSaved(drama.id);
if (nowSaved != wasSaved) {
_favoriteCountDelta += nowSaved ? 1 : -1;
notify();
}
return true;
return favorites.toggle(drama.id, card: drama);
}
@override
+10 -3
View File
@@ -164,7 +164,9 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
),
),
if (_tagValues(context, drama).isNotEmpty)
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(context, drama))),
SliverToBoxAdapter(
child: DramaTags(tags: _tagValues(context, drama)),
),
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
@@ -396,11 +398,14 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
}
Future<void> _toggleFavorite(AppLocalizations l10n) async {
if (!await ensureSignedIn(context)) return;
if (!mounted) return;
unawaited(context.read<Haptics>().lightImpact());
final ok = await logic.toggleFavorite();
if (ok || !mounted) return;
if (logic.favorites.lastErrorCode == 200007) {
await ensureSignedIn(context);
return;
}
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.favoriteToggleFailed)));
@@ -443,7 +448,9 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
}
List<String> _tagValues(BuildContext context, Drama drama) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
final localized = drama.localizedTypeLabels(
Localizations.localeOf(context).languageCode,
);
final result = <String>[];
if (localized.isNotEmpty) {
result.addAll(localized.take(_maxTags));
@@ -94,7 +94,7 @@ class _DramaEpisodesLoadingState extends State<DramaEpisodesLoading>
opacity: _opacity,
child: Container(
decoration: BoxDecoration(
color: AppColors.raised,
color: AppColors.skeletonMedia,
borderRadius: BorderRadius.circular(_radius),
),
),
+6 -10
View File
@@ -6,7 +6,6 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/data/services/favorite_controller.dart';
import '../../core/formatting/count_format.dart';
import '../../core/formatting/error_text.dart';
@@ -77,11 +76,6 @@ class _FavoritesContentState extends State<FavoritesContent> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
final signedIn = context.watch<AuthController>().isSignedIn;
if (!signedIn) {
_requested = false;
return;
}
if (_requested) return;
_requested = true;
final favorites = context.read<FavoriteController>();
@@ -93,7 +87,6 @@ class _FavoritesContentState extends State<FavoritesContent> {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final signedIn = context.watch<AuthController>().isSignedIn;
return SafeArea(
bottom: false,
child: Column(
@@ -104,9 +97,9 @@ class _FavoritesContentState extends State<FavoritesContent> {
showBack: widget.showBack,
),
Expanded(
child: signedIn
? _FavoritesBody(favorites: context.watch<FavoriteController>())
: const AuthGatePanel(),
child: _FavoritesBody(
favorites: context.watch<FavoriteController>(),
),
),
],
),
@@ -122,6 +115,9 @@ class _FavoritesBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
if (favorites.lastErrorCode == 200007) {
return const AuthGatePanel();
}
if (favorites.loading && favorites.cards.isEmpty) {
return const Center(
child: CircularProgressIndicator(key: Key('favorites-loading')),
@@ -27,6 +27,7 @@ const double _barButtonHeight = 30;
const double _removeDialogButtonHeight = 32;
const double _removeDialogRadius = 6;
const double _removeDialogBottomInset = 8;
const double _cancelFollowingDialogPadding = 20;
/// 播放历史移除确认。只把移除按钮压矮。
Future<bool> confirmHistoryRemove(BuildContext context) async {
@@ -71,13 +72,32 @@ Future<bool> confirmCancelFollowing(BuildContext context) async {
return await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
contentPadding: const EdgeInsets.all(_cancelFollowingDialogPadding),
actionsPadding: const EdgeInsets.fromLTRB(
_cancelFollowingDialogPadding,
0,
_cancelFollowingDialogPadding,
_cancelFollowingDialogPadding,
),
content: Text(l10n.confirmCancelFollowing),
actions: [
TextButton(
style: TextButton.styleFrom(
visualDensity: VisualDensity.standard,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: const Size(0, _removeDialogButtonHeight),
padding: const EdgeInsets.symmetric(horizontal: 12),
),
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(l10n.cancel),
),
FilledButton(
style: FilledButton.styleFrom(
visualDensity: VisualDensity.standard,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: const Size(0, _removeDialogButtonHeight),
padding: const EdgeInsets.symmetric(horizontal: 12),
),
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(l10n.cancelFollowing),
),
+47 -44
View File
@@ -15,7 +15,6 @@ import '../../core/data/services/watch_records_controller.dart';
import '../../core/formatting/error_text.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_dimens.dart';
import '../../core/widgets/auth_gate.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../player/open_player.dart';
@@ -67,7 +66,7 @@ class _FollowingPageState extends State<FollowingPage> {
history: context.read<WatchHistoryRepository>(),
catalog: context.read<CatalogRepository>(),
);
if (_wasSignedIn) unawaited(_history.load());
unawaited(_history.load());
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(widget.favoriteController.load());
});
@@ -75,8 +74,16 @@ class _FollowingPageState extends State<FollowingPage> {
void _onAuthChanged() {
final signedIn = _auth.isSignedIn;
if (signedIn && !_wasSignedIn) unawaited(_history.load());
if (signedIn == _wasSignedIn) return;
_wasSignedIn = signedIn;
_leaveEditing();
_history.reset();
widget.favoriteController.clear();
unawaited(_reloadForIdentity());
}
Future<void> _reloadForIdentity() async {
await Future.wait([_history.load(), widget.favoriteController.load()]);
}
@override
@@ -104,7 +111,6 @@ class _FollowingPageState extends State<FollowingPage> {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final signedIn = context.watch<AuthController>().isSignedIn;
return ColoredBox(
key: const Key('following-page'),
color: AppColors.appBackground,
@@ -114,47 +120,44 @@ class _FollowingPageState extends State<FollowingPage> {
children: [
_header(l10n),
Expanded(
child: !signedIn
? const AuthGatePanel()
: PageView(
key: const Key('following-tab-pages'),
controller: _pageController,
onPageChanged: _onPageChanged,
children: [
FollowingKeepAliveTab(
child: FollowingFavoritesGrid(
controller: widget.favoriteController,
selection: FollowingFavoriteSelection(
editing: _editing,
selected: _selected,
onToggle: _toggleDrama,
),
scrollController: _favoriteScroll,
onGoHome: widget.onGoHome,
),
),
FollowingKeepAliveTab(
child: _HistoryList(
controller: _history,
editing: _editing,
scrollController: _historyScroll,
onListEmptied: _exitEditingIfEmpty,
),
),
],
child: PageView(
key: const Key('following-tab-pages'),
controller: _pageController,
onPageChanged: _onPageChanged,
children: [
FollowingKeepAliveTab(
child: FollowingFavoritesGrid(
controller: widget.favoriteController,
selection: FollowingFavoriteSelection(
editing: _editing,
selected: _selected,
onToggle: _toggleDrama,
),
scrollController: _favoriteScroll,
onGoHome: widget.onGoHome,
),
),
if (signedIn)
FollowingEditSlot(
tab: _tab,
editing: _editing,
favorites: widget.favoriteController,
selected: _selected,
actions: FollowingEditActions(
onToggleAll: _toggleAll,
onRemove: () => unawaited(_cancelSelected()),
),
),
FollowingKeepAliveTab(
child: _HistoryList(
controller: _history,
editing: _editing,
scrollController: _historyScroll,
onListEmptied: _exitEditingIfEmpty,
),
),
],
),
),
FollowingEditSlot(
tab: _tab,
editing: _editing,
favorites: widget.favoriteController,
selected: _selected,
actions: FollowingEditActions(
onToggleAll: _toggleAll,
onRemove: () => unawaited(_cancelSelected()),
),
),
],
),
),
@@ -297,7 +300,7 @@ class _FollowingPageState extends State<FollowingPage> {
final tab = FollowingTab.values[index];
_leaveEditing();
_tab.value = tab;
if (tab == FollowingTab.history && _auth.isSignedIn) {
if (tab == FollowingTab.history) {
unawaited(_history.load());
}
}
+12 -34
View File
@@ -12,7 +12,6 @@ import '../../core/data/services/home_feed_controller.dart';
import '../../core/data/services/catalog_controller.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/data/services/favorite_controller.dart';
import '../../core/data/services/wallet_controller.dart';
import '../../core/platform/haptics.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_theme.dart';
@@ -20,16 +19,13 @@ import '../../core/widgets/auth_gate.dart';
import '../../core/widgets/app_root_tab.dart';
import '../discover/search_page.dart';
import '../following/following_page.dart';
import '../filter/filter_page.dart';
import '../mine/mine_types.dart';
import '../recommend/recommend_page.dart';
import '../recommend/recommend_discover_page.dart';
import '../mine/mine_view.dart';
import '../store/vip_page.dart';
import '../wallet/wallet_page.dart';
import 'home_binding.dart';
import 'home_logic.dart';
import 'widgets/home_feed_grid.dart';
import 'widgets/home_grid_header.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@@ -176,8 +172,8 @@ class _HomeTabsState extends State<_HomeTabs> {
Widget _body(BuildContext context) {
final pages = <Widget>[
_homeGrid(context),
_recommend(context),
_recommendDiscover(context),
FollowingPage(
onGoHome: () => logic.select(0),
favoriteController: context.read<FavoriteController>(),
@@ -194,27 +190,23 @@ class _HomeTabsState extends State<_HomeTabs> {
);
}
Widget _homeGrid(BuildContext context) {
return HomeFeedGrid(
feedController: widget.feedController,
callbacks: HomeGridCallbacks(
onSearch: () => _openSearch(context),
onOpenVip: () => unawaited(_openVip(context)),
onOpenWallet: () => unawaited(_openWallet(context)),
onOpenFilter: () => _pushPage(context, const FilterPage()),
),
onOpenDrama: (drama) => unawaited(logic.playDrama(context, drama)),
);
}
Widget _recommend(BuildContext context) {
return RecommendPage(
feedController: widget.feedController,
catalogApi: _catalogApi(context),
active: logic.tab == 1,
active: logic.tab == 0,
videoOnly: logic.videoImmersive,
onImmersiveChanged: logic.onImmersiveChanged,
onSearch: () => _openSearch(context),
onOpenWallet: () => unawaited(_openWallet(context)),
);
}
Widget _recommendDiscover(BuildContext context) {
return RecommendDiscoverPage(
active: logic.tab == 1,
onSearch: () => _openSearch(context),
onOpenWallet: () => unawaited(_openWallet(context)),
);
}
@@ -232,20 +224,6 @@ class _HomeTabsState extends State<_HomeTabs> {
).push<void>(MaterialPageRoute(builder: (_) => const SearchPage()));
}
void _pushPage(BuildContext context, Widget page) {
Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => page));
}
Future<void> _openVip(BuildContext context) async {
if (!await ensureSignedIn(context) || !context.mounted) return;
final wallet = context.read<WalletController>();
await Navigator.of(context).push<void>(
MaterialPageRoute(
builder: (_) => VipPage(onPurchased: () => unawaited(wallet.load())),
),
);
}
Future<void> _openWallet(BuildContext context) async {
if (!await ensureSignedIn(context) || !context.mounted) return;
await Navigator.of(
+1 -1
View File
@@ -50,7 +50,7 @@ class HomeFeedCard extends StatelessWidget {
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
style: const TextStyle(
color: AppColors.navSelected,
color: AppColors.textPrimary,
fontSize: AppDimens.cardTitleFont,
fontWeight: FontWeight.w500,
height: AppDimens.cardTitleLineHeight,
@@ -104,6 +104,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
return _categoryPlaceholder(
l10n,
context.watch<CategoryController>(),
catalog,
);
}
final category = shortcuts[index];
@@ -146,7 +147,11 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
Widget _categoryPlaceholder(
AppLocalizations l10n,
CategoryController controller,
CatalogController catalog,
) {
if (catalog.error != null) {
return _catalogErrorState(l10n, catalog);
}
if (controller.loading) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
+20 -3
View File
@@ -18,6 +18,7 @@ class MineLogic extends ChangeNotifier {
bool recentLoading = false;
String? recentError;
bool _disposed = false;
int _requestSeq = 0;
void notify() {
if (!_disposed) notifyListeners();
@@ -25,21 +26,37 @@ class MineLogic extends ChangeNotifier {
/// 最近观看:取分页首屏,剧名封面仍由目录卡片按 id 映射。
Future<void> refreshRecent() async {
final request = ++_requestSeq;
recentLoading = true;
recentError = null;
notify();
try {
final page = await history.recent(pageIndex: 1, pageSize: 10);
if (_disposed || request != _requestSeq) return;
recent = page.list;
watchRecordTotal = page.total;
} catch (_) {
recentError = 'progressError';
if (!_disposed && request == _requestSeq) {
recentError = 'progressError';
}
} finally {
recentLoading = false;
notify();
if (!_disposed && request == _requestSeq) {
recentLoading = false;
notify();
}
}
}
/// 切换账号/设备身份时先清空,避免旧身份数据回写或短暂混显。
void resetRecent() {
_requestSeq += 1;
recent = const [];
watchRecordTotal = null;
recentLoading = false;
recentError = null;
notify();
}
/// 页面重新可见时刷新最近观看,避免停留在旧进度。
void syncPage({required bool active, required bool wasActive}) {
if (active && !wasActive) refreshRecent();
+100 -11
View File
@@ -6,8 +6,11 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/models/watch_progress.dart';
import '../../core/data/repositories/watch_history_repository.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/data/services/catalog_controller.dart';
import '../../core/data/services/favorite_controller.dart';
import '../../core/data/services/locale_controller.dart';
import '../../core/data/services/wallet_controller.dart';
@@ -22,6 +25,7 @@ import '../downloads/downloads_page.dart';
import '../account/account_profile_page.dart';
import '../filter/filter_page.dart';
import '../notices/notices_page.dart';
import '../player/open_player.dart';
import '../settings/settings_page.dart';
import '../store/vip_page.dart';
import '../wallet/wallet_page.dart';
@@ -53,25 +57,70 @@ class MyPage extends StatefulWidget {
class _MyPageState extends State<MyPage> {
late final MineLogic logic;
late final AuthController _auth;
late final FavoriteController _favorites;
late bool _wasSignedIn;
bool _activationRefreshScheduled = false;
bool get embedded => widget.callbacks.embedded;
@override
void initState() {
super.initState();
_auth = context.read<AuthController>();
_favorites = context.read<FavoriteController>();
_wasSignedIn = _auth.isSignedIn;
_auth.addListener(_onAuthChanged);
logic = MineBinding().create(
history: context.read<WatchHistoryRepository>(),
);
if (widget.active) _scheduleFavoriteLoad();
}
@override
void didUpdateWidget(covariant MyPage oldWidget) {
super.didUpdateWidget(oldWidget);
logic.syncPage(active: widget.active, wasActive: oldWidget.active);
if (widget.active && !oldWidget.active) {
_scheduleActivationRefresh();
}
}
void _scheduleFavoriteLoad() {
if (_activationRefreshScheduled) return;
_activationRefreshScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_activationRefreshScheduled = false;
if (mounted) unawaited(_favorites.load());
});
}
void _scheduleActivationRefresh() {
if (_activationRefreshScheduled) return;
_activationRefreshScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_activationRefreshScheduled = false;
if (!mounted || !widget.active) return;
logic.syncPage(active: true, wasActive: false);
unawaited(_favorites.load());
});
}
void _onAuthChanged() {
final signedIn = _auth.isSignedIn;
if (signedIn == _wasSignedIn) return;
_wasSignedIn = signedIn;
logic.resetRecent();
_favorites.clear();
unawaited(_reloadForIdentity());
}
Future<void> _reloadForIdentity() async {
await Future.wait([logic.refreshRecent(), _favorites.load()]);
}
@override
void dispose() {
_auth.removeListener(_onAuthChanged);
logic.dispose();
super.dispose();
}
@@ -141,12 +190,14 @@ class _MyPageState extends State<MyPage> {
final wallet = context.watch<WalletController>();
final continueWatching = logic.recent.take(10).toList(growable: false);
final followingCount =
auth.isSignedIn &&
favorites.error == null &&
!(favorites.loading && favorites.total == 0)
favorites.error == null && !(favorites.loading && favorites.total == 0)
? favorites.total
: null;
final watchRecordCount = auth.isSignedIn ? logic.watchRecordTotal : null;
final watchRecordCount =
logic.recentError == null &&
!(logic.recentLoading && logic.watchRecordTotal == null)
? logic.watchRecordTotal
: null;
final coinBalance = auth.isSignedIn && wallet.snapshot != null
? wallet.balance
: null;
@@ -175,6 +226,7 @@ class _MyPageState extends State<MyPage> {
const SizedBox(height: AppDimens.mineSectionGap),
MineContinueWatching(
records: continueWatching,
onOpenRecord: _openContinueRecord,
onOpenAll: _openHistoryTab,
),
],
@@ -216,7 +268,7 @@ class _MyPageState extends State<MyPage> {
void _openDestination(MineDestination destination) {
switch (destination) {
case MineDestination.history:
_push(const WatchRecordsPage());
unawaited(_openHistoryPage());
case MineDestination.downloads:
_push(const DownloadsPage());
case MineDestination.wallet:
@@ -244,15 +296,52 @@ class _MyPageState extends State<MyPage> {
callback();
return;
}
_push(const WatchRecordsPage());
unawaited(_openHistoryPage());
}
void _push(Widget page) {
Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => page));
/// 继续观看卡片:补齐剧集后直接进全屏播放页,播放器自己会定位到记录的秒数。
Future<void> _openContinueRecord(WatchProgress record) async {
final catalog = context.read<CatalogController>();
// 续看记录只有剧的概要信息,先拼一个占位对象让目录去取完整详情
final summary = Drama(
id: record.dramaId,
title: record.dramaTitle ?? '',
synopsis: '',
posterUrl: record.dramaCover ?? '',
);
Drama drama;
try {
drama = await catalog.requireDetail(summary);
} catch (_) {
if (!mounted) return;
final l10n = AppLocalizations.of(context)!;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.detailLoadFailed)));
return;
}
if (!mounted) return;
await playDramaFromCatalog(
context,
drama,
episodeId: record.episodeId.isEmpty ? null : record.episodeId,
);
if (mounted) unawaited(logic.refreshRecent());
}
Future<void> _openHistoryPage() async {
await _push(const WatchRecordsPage());
if (mounted) unawaited(logic.refreshRecent());
}
Future<void> _push(Widget page) {
return Navigator.of(
context,
).push<void>(MaterialPageRoute(builder: (_) => page));
}
void _pushPlaceholder() {
_push(const _MinePlaceholderPage());
unawaited(_push(const _MinePlaceholderPage()));
}
Future<void> _openProtected(Widget page) async {
@@ -260,7 +349,7 @@ class _MyPageState extends State<MyPage> {
await ensureSignedIn(context);
return;
}
if (mounted) _push(page);
if (mounted) await _push(page);
}
void _openVip() {
@@ -12,10 +12,14 @@ class MineContinueWatching extends StatelessWidget {
const MineContinueWatching({
super.key,
required this.records,
required this.onOpenRecord,
required this.onOpenAll,
});
final List<WatchProgress> records;
/// 单张卡片:直接进入该剧的播放页,并定位到记录的集。
final ValueChanged<WatchProgress> onOpenRecord;
final VoidCallback onOpenAll;
@override
@@ -94,7 +98,11 @@ class MineContinueWatching extends StatelessWidget {
);
}
Widget _card(AppLocalizations l10n, WatchProgress record, String languageCode) {
Widget _card(
AppLocalizations l10n,
WatchProgress record,
String languageCode,
) {
final title = record.localizedTitle(languageCode).trim();
final episode = record.episodeNumber;
final hasProgress = record.duration > Duration.zero;
@@ -103,7 +111,7 @@ class MineContinueWatching extends StatelessWidget {
child: InkWell(
key: Key('mine-continue-${record.dramaId}'),
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
onTap: onOpenAll,
onTap: () => onOpenRecord(record),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -432,7 +432,7 @@ class _NewReleasesPageState extends State<NewReleasesPage> {
),
),
),
const SizedBox(height: 6),
const SizedBox(height: 4),
Text(
drama.title,
maxLines: 1,
+2 -12
View File
@@ -1,24 +1,14 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/services/auth_controller.dart';
import '../../core/widgets/auth_gate.dart';
/// 评论入口统一登录闸:登录成功且页面仍存在时再打开评论面板。
Future<void> openCommentsWithAuth(
/// 评论列表与非付费互动均支持设备身份,不再把登录作为入口前置条件。
Future<void> openComments(
BuildContext context,
Drama drama, {
required Future<void> Function(BuildContext context, Drama drama) show,
}) async {
final auth = context.read<AuthController>();
if (auth.isSignedIn) {
await show(context, drama);
return;
}
await ensureSignedIn(context);
if (!context.mounted || !auth.isSignedIn) return;
await show(context, drama);
}
+2
View File
@@ -15,6 +15,7 @@ class PlayerBinding {
required PlaybackPositionCache positionCache,
WalletController? wallet,
DownloadController? downloads,
bool Function()? isSignedIn,
}) => PlayerLogic(
history: history,
playback: playback,
@@ -22,5 +23,6 @@ class PlayerBinding {
pictureInPicture: AndroidPictureInPicture(),
wallet: wallet,
downloads: downloads,
isSignedIn: isSignedIn,
);
}
+319 -16
View File
@@ -2,12 +2,14 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter/scheduler.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/models/episode_stats.dart';
import '../../core/data/models/play_ticket.dart';
import '../../core/data/models/watch_progress.dart';
import '../../core/data/models/player_port.dart';
@@ -50,9 +52,13 @@ class PlayerLogic extends ChangeNotifier {
this.downloads,
PlaybackPositionCache? positionCache,
Future<void> Function()? waitForFrame,
DateTime Function()? clock,
bool Function()? isSignedIn,
}) : positionCache = positionCache ?? PlaybackPositionCache(),
_waitForFrame =
waitForFrame ?? (() => WidgetsBinding.instance.endOfFrame);
waitForFrame ?? (() => WidgetsBinding.instance.endOfFrame),
_clock = clock ?? DateTime.now,
_isSignedIn = isSignedIn ?? (() => true);
final WatchHistoryRepository history;
final PlaybackRepository playback;
@@ -61,6 +67,8 @@ class PlayerLogic extends ChangeNotifier {
final DownloadController? downloads;
final PlaybackPositionCache positionCache;
final Future<void> Function() _waitForFrame;
final DateTime Function() _clock;
final bool Function() _isSignedIn;
late PageController pages;
late PlaybackQueue queue;
@@ -93,13 +101,24 @@ class PlayerLogic extends ChangeNotifier {
String selectedQuality = 'AUTO';
Duration? _qualitySeek;
int pageRequest = 0;
int? _pendingSelectionIndex;
int? _pendingSelectionRevision;
Future<void>? _selectionDrain;
bool muted = false;
double playbackSpeed = 1.0;
bool stoppedAtFeedEnd = false;
Duration episodeStatsTtl = const Duration(seconds: 60);
ValueChanged<EpisodeStats>? onEpisodeStatsUpdated;
VideoPlayerPort? scrubbingPlayer;
bool pip = false;
bool pipPreparing = false;
final Map<String, int> pickedEpisode = {};
final Set<String> _unlockedEpisodeIds = {};
final Map<String, EpisodeStats> _episodeStats = {};
final Map<String, DateTime> _episodeStatsFetchedAt = {};
final Map<String, Future<void>> _episodeStatsInFlight = {};
final Map<String, int> _episodeStatsRevision = {};
final Map<String, int> _dramaStatsRevision = {};
/// 解锁中的集 id 与失败文案;空表示没有进行中的解锁。
String? unlockingEpisodeId;
@@ -163,6 +182,8 @@ class PlayerLogic extends ChangeNotifier {
return fallback;
}
EpisodeStats? episodeStats(String episodeId) => _episodeStats[episodeId];
void notify() {
if (!_disposed) notifyListeners();
}
@@ -188,6 +209,7 @@ class PlayerLogic extends ChangeNotifier {
void start({
required PlayerFactory factory,
required PlaybackCoordinator coordinator,
bool initialUserWantsPlay = true,
}) {
_started = true;
_sessionFactory = factory;
@@ -205,7 +227,48 @@ class PlayerLogic extends ChangeNotifier {
session.setRouteVisible(false);
}
unawaited(loadResumePoint());
unawaited(selectEpisode(initialIndex));
unawaited(
selectEpisode(
initialIndex,
userWantsPlay: initialUserWantsPlay ? null : false,
),
);
}
/// 独立播放页覆盖首页时只暂停并保存进度,首页 session 与 controller 保持存活。
Future<void> pauseForFullPlayer() async {
if (!_started) return;
_logFeedHandoff('pause');
cancelScrub();
await session.pauseForRouteHandoff();
_logFeedHandoff('paused');
}
/// 独立播放页关闭并恢复首页路由后,等原生播放器实际恢复再结束交接。
Future<void> resumeAfterFullPlayer() async {
if (!_started) return;
_logFeedHandoff('resume');
if (visibleIndices.isNotEmpty) {
await session.resumeForRouteHandoff();
} else {
session.setRouteVisible(false);
await session.playbackSettled;
}
_logFeedHandoff('resumed');
}
void _logFeedHandoff(String phase) {
if (!kDebugMode) return;
final player = session.active;
final video = player is VideoPlayerPort ? player : null;
debugPrint(
'[feed-session] phase=$phase session=${identityHashCode(session)} '
'index=${session.currentIndex} episode=${session.currentEpisode.id} '
'controller=${video == null ? '-' : identityHashCode(video.controller)} '
'user=${session.userWantsPlay} routeVisible=${session.debugRouteVisible} '
'appResumed=${session.debugAppResumed} overlayOpen=${session.debugOverlayOpen} '
'live=${session.livePlayerCount}',
);
}
/// 串行替换首页 feed 队列;频道变化时重置到第 1 个,刷新时尽量保留当前剧。
@@ -238,11 +301,16 @@ class PlayerLogic extends ChangeNotifier {
episodes: sessionEpisodes,
factory: factory,
// 地址只由后端下发(票据或详情里的免费集签名地址),拿不到地址即视为锁定
canPlay: (episode) => episode.videoUrl.isNotEmpty,
canPlay: (episode) =>
episode.videoUrl.isNotEmpty && !isEpisodeLocked(episode),
prepare: preparePlayer,
activate: activatePlayer,
coordinator: coordinator,
waitForFrame: _waitForFrame,
owner: homeMode ? PlaybackSessionOwner.home : PlaybackSessionOwner.player,
dramaIdAt: (index) => index >= 0 && index < queue.length
? queue.entryAt(index).drama.id
: null,
);
}
@@ -428,6 +496,7 @@ class PlayerLogic extends ChangeNotifier {
final localPath = await downloads?.findLocalPath(episode.id);
if (request != pageRequest) return false;
if (localPath != null) {
_unlockedEpisodeIds.add(episode.id);
blockedTicket = null;
blockedEpisodeId = null;
qualities = const [];
@@ -452,12 +521,14 @@ class PlayerLogic extends ChangeNotifier {
final playUrl = preferred ?? ticket.playUrl;
if (preferred == null) selectedQuality = 'AUTO';
if (ticket.accessible && playUrl.isNotEmpty) {
_unlockedEpisodeIds.add(episode.id);
// 签名地址原样写回,不做任何拼接/改写(AppConfig.mediaUrl 只补 host)
sessionEpisodes[index] = episode.withVideoUrl(
playUrl,
likeCount: ticket.likeCount,
commentCount: ticket.commentCount,
thumbnailsUrl: ticket.thumbnailsUrl,
posterUrl: ticket.posterUrl,
);
return true;
}
@@ -467,7 +538,7 @@ class PlayerLogic extends ChangeNotifier {
} catch (exception) {
if (request != pageRequest) return false;
// 详情里已有可用地址(免费集)时降级继续,避免票据服务抖动就完全看不了
if (episode.videoUrl.isNotEmpty) {
if (episode.videoUrl.isNotEmpty && !isEpisodeLocked(episode)) {
ticketError = null;
return true;
}
@@ -481,6 +552,160 @@ class PlayerLogic extends ChangeNotifier {
}
}
/// 当前集激活后刷新轻量互动计数;同集命中 TTL 或已有请求时不重复发请求。
Future<void> refreshEpisodeStats(int index) {
if (_disposed || index < 0 || index >= sessionEpisodes.length) {
return Future<void>.value();
}
final episodeId = sessionEpisodes[index].id;
final cached = _episodeStats[episodeId];
final fetchedAt = _episodeStatsFetchedAt[episodeId];
if (cached != null &&
fetchedAt != null &&
_clock().difference(fetchedAt) < episodeStatsTtl) {
_logEpisodeStatsRefresh(episodeId, cached: true);
onEpisodeStatsUpdated?.call(cached);
return Future<void>.value();
}
final inFlight = _episodeStatsInFlight[episodeId];
if (inFlight != null) {
_logEpisodeStatsRefresh(episodeId, cached: true, inFlight: true);
return inFlight;
}
_logEpisodeStatsRefresh(episodeId, cached: false);
final expectedDramaId = index < queue.length
? queue.entryAt(index).drama.id
: '';
final episodeRevision = _episodeStatsRevision[episodeId] ?? 0;
final dramaRevision = _dramaStatsRevision[expectedDramaId] ?? 0;
late final Future<void> request;
request =
_fetchEpisodeStats(
episodeId,
expectedDramaId: expectedDramaId,
episodeRevision: episodeRevision,
dramaRevision: dramaRevision,
).whenComplete(() {
if (identical(_episodeStatsInFlight[episodeId], request)) {
_episodeStatsInFlight.remove(episodeId);
}
});
_episodeStatsInFlight[episodeId] = request;
return request;
}
Future<void> _fetchEpisodeStats(
String episodeId, {
required String expectedDramaId,
required int episodeRevision,
required int dramaRevision,
}) async {
try {
final fetched = await playback.episodeStats(episodeId);
if (_disposed) return;
if ((_episodeStatsRevision[episodeId] ?? 0) != episodeRevision ||
(_dramaStatsRevision[expectedDramaId] ?? 0) != dramaRevision) {
if (kDebugMode) {
debugPrint(
'[player] phase=episode-stats-discarded episodeId=$episodeId '
'reason=local-state-newer',
);
}
return;
}
final stats = fetched.copyWith(
dramaId: fetched.dramaId.isEmpty ? expectedDramaId : fetched.dramaId,
);
_episodeStats[episodeId] = stats;
_episodeStatsFetchedAt[episodeId] = _clock();
final episodeIndex = sessionEpisodes.indexWhere(
(episode) => episode.id == episodeId,
);
if (episodeIndex >= 0) {
sessionEpisodes[episodeIndex] = sessionEpisodes[episodeIndex].withStats(
likeCount: stats.likeCount,
commentCount: stats.commentCount,
);
}
onEpisodeStatsUpdated?.call(stats);
notify();
} catch (_) {
// 统计接口只负责校准计数,失败时保留播放与旧值。
}
}
void _logEpisodeStatsRefresh(
String episodeId, {
required bool cached,
bool inFlight = false,
}) {
if (!kDebugMode) return;
debugPrint(
'[player] phase=episode-stats-refresh episodeId=$episodeId '
'cached=${cached ? 1 : 0}${inFlight ? ' inFlight=1' : ''}',
);
}
/// 点赞成功后同步本地统计快照,避免切回时被旧缓存覆盖。
void applyEpisodeLikeState(
String episodeId, {
required bool liked,
required int likeCount,
}) {
_episodeStatsRevision.update(
episodeId,
(value) => value + 1,
ifAbsent: () => 1,
);
final stats = _episodeStats[episodeId];
if (stats != null) {
_episodeStats[episodeId] = stats.copyWith(
liked: liked,
likeCount: likeCount,
);
}
final index = sessionEpisodes.indexWhere(
(episode) => episode.id == episodeId,
);
if (index >= 0) {
sessionEpisodes[index] = sessionEpisodes[index].withStats(
likeCount: likeCount,
);
}
notify();
}
/// 评论面板关闭后同步评论数。
void applyEpisodeCommentCount(String episodeId, int commentCount) {
_episodeStatsRevision.update(
episodeId,
(value) => value + 1,
ifAbsent: () => 1,
);
final stats = _episodeStats[episodeId];
if (stats != null) {
_episodeStats[episodeId] = stats.copyWith(commentCount: commentCount);
}
final index = sessionEpisodes.indexWhere(
(episode) => episode.id == episodeId,
);
if (index >= 0) {
sessionEpisodes[index] = sessionEpisodes[index].withStats(
commentCount: commentCount,
);
}
notify();
}
/// 收藏成功后让旧 stats 请求失效,计数本身只写 FavoriteController。
void markDramaFavoriteChanged(String dramaId) {
_dramaStatsRevision.update(
dramaId,
(value) => value + 1,
ifAbsent: () => 1,
);
}
String _fileUrl(String path) =>
path.startsWith('file:') ? path : Uri.file(path).toString();
@@ -553,7 +778,10 @@ class PlayerLogic extends ChangeNotifier {
/// 金币解锁当前集;成功后强制刷新票据并直接起播。
Future<bool> unlockEpisode(int index) async {
final service = wallet;
if (service == null || index < 0 || index >= sessionEpisodes.length) {
if (service == null ||
!_isSignedIn() ||
index < 0 ||
index >= sessionEpisodes.length) {
return false;
}
final episode = sessionEpisodes[index];
@@ -566,6 +794,7 @@ class PlayerLogic extends ChangeNotifier {
unlockError = service.unlockError;
return false;
}
_unlockedEpisodeIds.add(episode.id);
final ready = await ensureTicket(index, forceRefresh: true);
if (ready) {
await _selectVisible(index);
@@ -951,7 +1180,43 @@ class PlayerLogic extends ChangeNotifier {
);
}
Future<void> selectEpisode(int index, {int? revision}) async {
/// 翻页入口使用 single-flight:执行中的切集不被重复排队,只保留最新目标。
Future<void> requestEpisodeSelection(int index, {int? revision}) {
if (_disposed || index < 0 || index >= sessionEpisodes.length) {
return Future<void>.value();
}
_pendingSelectionIndex = index;
_pendingSelectionRevision = revision;
return _selectionDrain ??= _drainEpisodeSelections();
}
Future<void> _drainEpisodeSelections() async {
try {
while (!_disposed) {
final index = _pendingSelectionIndex;
if (index == null) break;
final revision = _pendingSelectionRevision;
_pendingSelectionIndex = null;
_pendingSelectionRevision = null;
await selectEpisode(index, revision: revision);
}
} finally {
_selectionDrain = null;
final index = _pendingSelectionIndex;
if (!_disposed && index != null) {
unawaited(
requestEpisodeSelection(index, revision: _pendingSelectionRevision),
);
}
}
}
Future<void> selectEpisode(
int index, {
int? revision,
bool? userWantsPlay,
}) async {
if (index < 0 || index >= sessionEpisodes.length) return;
final feedRevisionAtStart = revision ?? feedRevision;
final request = ++pageRequest;
cancelScrub();
@@ -962,6 +1227,26 @@ class PlayerLogic extends ChangeNotifier {
!isMounted()) {
return;
}
final episode = sessionEpisodes[index];
if (isEpisodeLocked(episode)) {
blockedTicket = null;
blockedEpisodeId = episode.id;
ticketError = null;
await session.selectLocked(
index,
preloadIndex: nextVisibleIndex(index),
previousIndex: previousVisibleIndex(index),
);
if (request != pageRequest ||
feedRevisionAtStart != feedRevision ||
!isMounted()) {
return;
}
if (!_isSignedIn()) {
unawaited(refreshEpisodeStats(index));
return;
}
}
// 起播前先要票据:拿不到就不起播,交给三态 UI 提示(失败可重试)
final ready = await ensureTicket(index);
if (request != pageRequest ||
@@ -969,17 +1254,30 @@ class PlayerLogic extends ChangeNotifier {
!isMounted()) {
return;
}
if (!ready && ticketError != null) return;
await _selectVisible(index);
if (!ready) {
unawaited(refreshEpisodeStats(index));
return;
}
await _selectVisible(index, userWantsPlay: userWantsPlay);
}
/// 收费集只有在本会话确认可播或解锁成功后才解除门禁。
bool isEpisodeLocked(Episode episode) {
return (episode.locked || !episode.isFree) &&
!_unlockedEpisodeIds.contains(episode.id);
}
/// 按可见队列选择一集,并预热上一集与下一集。
Future<void> _selectVisible(int index) {
return session.select(
Future<void> _selectVisible(int index, {bool? userWantsPlay}) async {
await session.select(
index,
preloadIndex: nextVisibleIndex(index),
previousIndex: previousVisibleIndex(index),
userWantsPlay: userWantsPlay,
);
if (!_disposed && session.currentIndex == index) {
unawaited(refreshEpisodeStats(index));
}
}
int? nextVisibleIndex(int index) {
@@ -1113,12 +1411,10 @@ class PlayerLogic extends ChangeNotifier {
Drama drama,
int index,
) async {
session.setRouteVisible(false);
await session.playbackSettled;
await saveCurrentProgress();
if (!context.mounted) return;
await Navigator.of(context).push(
final route = Navigator.of(context).push(
FadePageRoute<void>(
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
builder: (_) => PlayerPage(
drama: drama,
initialIndex: index,
@@ -1127,7 +1423,14 @@ class PlayerLogic extends ChangeNotifier {
),
),
);
if (isMounted()) session.setRouteVisible(active);
if (kDebugMode) {
debugPrint('[player-entry] phase=route-pushed source=watch-all ms=0');
}
unawaited(pauseForFullPlayer());
unawaited(saveCurrentProgress());
await route;
if (!isMounted()) return;
await resumeAfterFullPlayer();
}
Future<void> showEpisodes(BuildContext context) async {
File diff suppressed because it is too large. Load diff
+54 -11
View File
@@ -65,6 +65,11 @@ extension _PlayerViewActions on _PlayerPageState {
) async {
final wallet = logic.wallet;
if (wallet == null) return;
if (!context.read<AuthController>().isSignedIn &&
!await ensureSignedIn(context)) {
return;
}
if (!context.mounted) return;
await showModalBottomSheet<bool>(
context: context,
backgroundColor: AppColors.transparent,
@@ -81,7 +86,7 @@ extension _PlayerViewActions on _PlayerPageState {
}
Future<bool> _unlockEpisode(BuildContext context, int index) async {
if (!await ensureSignedIn(context) || !context.mounted) return false;
if (!context.read<AuthController>().isSignedIn) return false;
final ok = await logic.unlockEpisode(index);
if (ok || !context.mounted) return ok;
final l10n = AppLocalizations.of(context)!;
@@ -99,18 +104,53 @@ extension _PlayerViewActions on _PlayerPageState {
Episode episode, {
bool likeOnly = false,
}) async {
unawaited(context.read<Haptics>().lightImpact());
if (interactions.isEpisodeBusy(episode.id) ||
(likeOnly && interactions.isEpisodeLiked(episode.id))) {
return;
final busyBefore = interactions.isEpisodeBusy(episode.id);
final likedBefore = interactions.isEpisodeLiked(episode.id);
if (kDebugMode) {
debugPrint(
'[player-like] phase=toggle-start '
'episodeId=${episode.id} likeOnly=$likeOnly '
'busy=$busyBefore liked=$likedBefore',
);
}
if (!await ensureSignedIn(context) || !context.mounted) return;
if (interactions.isEpisodeBusy(episode.id) ||
(likeOnly && interactions.isEpisodeLiked(episode.id))) {
unawaited(context.read<Haptics>().lightImpact());
if (busyBefore || (likeOnly && likedBefore)) {
if (kDebugMode) {
debugPrint(
'[player-like] phase=toggle-skipped '
'episodeId=${episode.id} '
'reason=${busyBefore ? 'busy' : 'already-liked'}',
);
}
return;
}
final result = await interactions.toggleEpisodeLike(episode.id);
if (result.isSuccess || !context.mounted) return;
if (kDebugMode) {
debugPrint(
'[player-like] phase=toggle-result '
'episodeId=${episode.id} success=${result.isSuccess} '
'liked=${interactions.isEpisodeLiked(episode.id)} '
'count=${interactions.episodeLikeCount(episode.id)} '
'error=${result.errorMessage ?? '-'}',
);
}
if (result.isSuccess) {
final likeCount = interactions.episodeLikeCount(episode.id);
if (likeCount != null) {
logic.applyEpisodeLikeState(
episode.id,
liked: interactions.isEpisodeLiked(episode.id),
likeCount: likeCount,
);
}
_refreshLikeState();
return;
}
if (!context.mounted) return;
if (result.errorCode == 200007) {
await ensureSignedIn(context);
return;
}
showCenteredToast(
context,
result.errorMessage ?? AppLocalizations.of(context)!.likeFailed,
@@ -119,7 +159,6 @@ extension _PlayerViewActions on _PlayerPageState {
Future<void> _toggleSave(BuildContext context, Drama drama) async {
final favorites = context.read<FavoriteController>();
if (!await ensureSignedIn(context) || !context.mounted) return;
unawaited(context.read<Haptics>().lightImpact());
final wasSaved = favorites.isSaved(drama.id);
final ok = await favorites.toggle(drama.id, card: drama);
@@ -127,10 +166,14 @@ extension _PlayerViewActions on _PlayerPageState {
if (ok) {
final nowSaved = favorites.isSaved(drama.id);
if (nowSaved != wasSaved) {
_applyFavoriteDelta(drama.id, nowSaved: nowSaved);
logic.markDramaFavoriteChanged(drama.id);
}
return;
}
if (favorites.lastErrorCode == 200007) {
await ensureSignedIn(context);
return;
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.favoriteToggleFailed),
@@ -9,7 +9,6 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../../core/data/models/comment.dart';
import '../../../core/data/services/auth_controller.dart';
import '../../../core/data/services/comment_controller.dart';
import '../../../core/platform/haptics.dart';
import '../../../core/platform/keyboard_inset.dart';
@@ -196,23 +195,20 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
return;
}
final l10n = AppLocalizations.of(context)!;
if (result.errorCode == 200007) {
await ensureSignedIn(context);
return;
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result.errorMessage ?? l10n.commentPostFailed)),
);
}
Future<void> _authenticate() async {
await ensureSignedIn(context);
if (!mounted || !context.read<AuthController>().isSignedIn) return;
_inputFocus.requestFocus();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final signedIn = context.watch<AuthController>().isSignedIn;
final hasContent = _input.text.trim().isNotEmpty;
final canPost = signedIn && hasContent && !widget.controller.submitting;
final canPost = hasContent && !widget.controller.submitting;
final multiline = _input.text.contains('\n');
final bottomInset = _isAndroid
? _pinnedKeyboardInset
@@ -247,8 +243,8 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
key: const Key('comment-composer-input'),
controller: _input,
focusNode: _inputFocus,
readOnly: !signedIn,
canRequestFocus: signedIn,
readOnly: false,
canRequestFocus: true,
minLines: 1,
maxLines: 4,
maxLength: _maxCommentLength,
@@ -262,9 +258,7 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
),
cursorColor: AppColors.blue,
decoration: InputDecoration(
hintText: signedIn
? l10n.writeComment
: l10n.commentLoginHint,
hintText: l10n.writeComment,
hintStyle: const TextStyle(
color: AppColors.muted,
fontSize: 14,
@@ -278,7 +272,7 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
),
onTap: signedIn ? null : _authenticate,
onTap: null,
),
),
const SizedBox(height: 12),
@@ -11,11 +11,9 @@ import '../../../core/data/models/comment.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/repositories/comment_repository.dart';
import '../../../core/data/repositories/interaction_repository.dart';
import '../../../core/data/services/auth_controller.dart';
import '../../../core/data/services/comment_controller.dart';
import '../../../core/formatting/error_text.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/auth_gate.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../l10n/app_localizations.dart';
import 'comment_composer_sheet.dart';
@@ -29,7 +27,7 @@ const double _sheetRadius = 20;
const double _headerHeight = 44;
const double _composerTopGap = 8;
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与登录发布。
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与设备身份发布。
class DramaCommentsSheet extends StatefulWidget {
const DramaCommentsSheet({super.key, required this.drama, this.episodeId});
@@ -92,8 +90,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
}
Future<void> _openComposer({DramaComment? replyTo}) async {
await ensureSignedIn(context);
if (!mounted || !context.read<AuthController>().isSignedIn) return;
if (!mounted) return;
_removeComposerOverlay();
final entry = OverlayEntry(
builder: (_) => CommentComposerSheet(
@@ -222,7 +219,6 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
Widget _content(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final count = _serverCount ?? _controller.exactCount;
final signedIn = context.watch<AuthController>().isSignedIn;
final composerReserve = _composerHeight + _composerTopGap;
return Column(
key: const Key('comment-sheet-content'),
@@ -269,7 +265,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
Padding(
key: const Key('comment-composer-area'),
padding: const EdgeInsets.only(top: _composerTopGap),
child: _fakeComposer(l10n, signedIn: signedIn),
child: _fakeComposer(l10n),
),
],
);
@@ -352,7 +348,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
return const SizedBox(height: 8);
}
Widget _fakeComposer(AppLocalizations l10n, {required bool signedIn}) {
Widget _fakeComposer(AppLocalizations l10n) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _openComposer,
@@ -372,7 +368,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
child: Padding(
padding: const EdgeInsets.only(left: 16),
child: Text(
signedIn ? l10n.writeComment : l10n.commentLoginHint,
l10n.writeComment,
key: const Key('comment-input-placeholder-label'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
+47 -134
View File
@@ -14,7 +14,7 @@ import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import 'home_feed_recommend_panel.dart';
import 'loading_progress_track.dart';
import 'player_double_tap_hearts.dart';
import 'player_tap_gesture_region.dart';
import 'seek_progress_bar.dart';
import 'scrub_preview_card.dart';
@@ -22,11 +22,13 @@ part 'home_feed_overlay_parts.dart';
const double _progressHeight = 2;
const double _progressHitHeight = 32;
const double _pageHorizontal = 14;
const double _railRight = 8;
const double _pageHorizontal = 20;
const double _railRight = 14;
const double _railGap = 12;
const double _bottomInfoInset = 32;
const double _railBottomOffset = 60;
// 观看条高 44;2pt 进度线视觉上沿距观看条顶约 7pt(线中心距进度条盒底 8)。
// 信息面板底边取 44+16=60,使简介↔进度线、进度线↔观看条两侧间距均为 7pt。
const double _bottomInfoInset = homeFeedWatchAllHeight + 16;
const double _railBottomOffset = 40;
const Duration _overlayFadeDuration = Duration(milliseconds: 120);
const List<Shadow> _boostTextShadows = [
Shadow(color: AppColors.shadow, blurRadius: 5, offset: Offset(0, 1)),
@@ -52,6 +54,7 @@ class HomeFeedOverlay extends StatefulWidget {
required this.onDetail,
required this.onOpenFullPlayer,
this.onEpisodes,
this.onOpenSearch,
required this.onTogglePlay,
required this.onBoostStart,
required this.onBoostEnd,
@@ -69,6 +72,7 @@ class HomeFeedOverlay extends StatefulWidget {
this.cancelScrubRequest = 0,
this.thumbnailService,
this.spriteAxisService,
this.suppressBufferLoading = false,
});
final AppLocalizations l10n;
@@ -91,6 +95,9 @@ class HomeFeedOverlay extends StatefulWidget {
final VoidCallback onDetail;
final VoidCallback onOpenFullPlayer;
final VoidCallback? onEpisodes;
/// 底部热搜胶囊点击(降级版:跳搜索页)。
final VoidCallback? onOpenSearch;
final VoidCallback onTogglePlay;
final VoidCallback onBoostStart;
final VoidCallback onBoostEnd;
@@ -104,25 +111,15 @@ class HomeFeedOverlay extends StatefulWidget {
final int cancelScrubRequest;
final PlaybackThumbnailService? thumbnailService;
final SpriteThumbnailAxisService? spriteAxisService;
final bool suppressBufferLoading;
@override
State<HomeFeedOverlay> createState() => _HomeFeedOverlayState();
}
class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
static const Duration _singleTapDelay = Duration(milliseconds: 400);
bool _scrubbing = false;
bool _wasVisibleBeforeScrub = true;
Timer? _singleTapTimer;
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 = [];
@override
void didUpdateWidget(covariant HomeFeedOverlay oldWidget) {
@@ -132,35 +129,24 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
}
}
@override
void dispose() {
_tapSeq++;
_singleTapTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SafeArea(
bottom: false,
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: LayoutBuilder(
builder: (context, constraints) => Listener(
onPointerUp: (_) => widget.onBoostEnd(),
onPointerCancel: (_) => widget.onBoostEnd(),
onPointerDown: _handlePointerDown,
child: GestureDetector(
key: const Key('home-feed-gesture'),
behavior: HitTestBehavior.opaque,
onTapUp: _handleTapUp,
onLongPressStart: (details) =>
_handleLongPressStart(details, constraints.maxWidth),
onLongPressEnd: (_) => widget.onBoostEnd(),
onLongPressCancel: widget.onBoostEnd,
),
),
child: PlayerTapGestureRegion(
key: const ValueKey('home-feed-tap-gesture-region'),
gestureKey: const Key('home-feed-gesture'),
enabled: !_scrubbing,
doubleTapEnabled: !widget.locked,
now: widget.now,
onSingleTap: widget.onTogglePlay,
onDoubleTapLike: widget.onDoubleTapLike,
onLongPressStart: _handleLongPressStart,
onInteractionEnd: widget.onBoostEnd,
),
),
Positioned(
@@ -193,7 +179,7 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
Positioned(
left: 0,
right: 0,
bottom: 20,
bottom: homeFeedWatchAllHeight + 12,
child: AnimatedOpacity(
duration: _overlayFadeDuration,
opacity: widget.boosting ? 1 : 0,
@@ -204,9 +190,9 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
),
),
Positioned(
left: 0,
right: 0,
bottom: 0,
left: _pageHorizontal,
right: _pageHorizontal,
bottom: homeFeedWatchAllHeight,
child: _FeedProgressBar(
controller: widget.controller,
locked: widget.locked,
@@ -217,31 +203,30 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
spriteAxisService: widget.spriteAxisService,
thumbnailsUrl: widget.episode.thumbnailsUrl,
episodeId: widget.episode.id,
posterUrl: widget.drama.posterUrl,
suppressBufferLoading: widget.suppressBufferLoading,
onScrubStart: _startScrub,
onScrubEnd: _endScrub,
onSeek: widget.onSeek,
),
),
if (_heartBursts.isNotEmpty)
Positioned.fill(
Positioned(
left: 0,
right: 0,
bottom: 0,
child: AnimatedOpacity(
duration: _overlayFadeDuration,
opacity: widget.visible && !_scrubbing && !widget.boosting
? 1
: 0,
child: IgnorePointer(
child: Stack(
clipBehavior: Clip.none,
children: [
for (final burst in _heartBursts)
Positioned(
left: burst.position.dx,
top: burst.position.dy - 10,
child: PlayerDoubleTapHeartBurst(
key: ValueKey(burst.id),
onCompleted: () => _removeHeartBurst(burst.id),
),
),
],
ignoring: !widget.visible || _scrubbing || widget.boosting,
child: HomeFeedWatchAllBar(
drama: widget.drama,
onTap: widget.onOpenFullPlayer,
),
),
),
),
],
),
);
@@ -263,83 +248,8 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
widget.onScrubEnd?.call(wasVisible);
}
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;
}
_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)) 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)));
widget.onDoubleTapLike?.call(position);
}
void _removeHeartBurst(int id) {
if (!mounted) return;
setState(() => _heartBursts.removeWhere((burst) => burst.id == id));
}
void _handleLongPressStart(LongPressStartDetails details, double width) {
final third = width / 3;
_tapSeq++;
_cancelPendingSingleTap();
_doubleTapDown = false;
_lastDownAt = null;
final dx = details.localPosition.dx;
if (dx < third || dx > width - third) {
widget.onBoostStart();
@@ -383,9 +293,11 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
liked: widget.liked,
favoriteCount: widget.favoriteCount,
likeCount: widget.likeCount,
commentCount: widget.commentCount,
onSave: widget.onSave,
onLike: widget.onLike,
onEpisodes: widget.onEpisodes ?? widget.onOpenFullPlayer,
onComments: widget.onComments,
onShare: widget.onShare,
);
}
@@ -395,6 +307,7 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
episode: widget.episode,
onDetail: widget.onDetail,
onOpenFullPlayer: widget.onOpenFullPlayer,
onOpenSearch: widget.onOpenSearch,
);
}
}
@@ -6,7 +6,6 @@ const double _thumbSize = 6;
const double _thumbActiveSize = 14;
const double _trackActiveHeight = 6;
const double _lineCenterFromBottom = 8;
const Duration _trackResizeDuration = Duration(milliseconds: 120);
const double _timeBubbleWidth = 96;
const double _timeBubbleMargin = 12;
const Key _inactiveTrackKey = Key('home-feed-progress-inactive');
@@ -23,7 +22,7 @@ class _FeedProgressBar extends StatefulWidget {
this.spriteAxisService,
this.thumbnailsUrl,
this.episodeId,
this.posterUrl = '',
this.suppressBufferLoading = false,
this.onScrubStart,
this.onScrubEnd,
this.onSeek,
@@ -38,7 +37,7 @@ class _FeedProgressBar extends StatefulWidget {
final SpriteThumbnailAxisSource? spriteAxisService;
final String? thumbnailsUrl;
final String? episodeId;
final String posterUrl;
final bool suppressBufferLoading;
final VoidCallback? onScrubStart;
final VoidCallback? onScrubEnd;
final ValueChanged<Duration>? onSeek;
@@ -54,6 +53,7 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
Timer? _bufferTimer;
bool _buffering = false;
bool _dragging = false;
Duration? _lastPosition;
@override
void initState() {
@@ -69,6 +69,7 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
_bufferTimer?.cancel();
_bufferTimer = null;
_buffering = false;
_lastPosition = null;
_attachSource();
}
if (oldWidget.cancelScrubRequest != widget.cancelScrubRequest) {
@@ -79,6 +80,7 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
_bufferTimer?.cancel();
_bufferTimer = null;
_buffering = false;
_lastPosition = null;
if (widget.locked) {
_dragging = false;
_preview = null;
@@ -86,6 +88,13 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
_syncBufferState(notify: false);
}
}
if (oldWidget.suppressBufferLoading != widget.suppressBufferLoading) {
_bufferTimer?.cancel();
_bufferTimer = null;
_buffering = false;
_lastPosition = null;
_syncBufferState(notify: false);
}
}
@override
@@ -102,7 +111,11 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
final width = constraints.maxWidth;
final source = widget.controller;
final scrubbing = _dragging;
final loading = !widget.locked && !scrubbing && _buffering;
final loading =
!widget.locked &&
!widget.suppressBufferLoading &&
!scrubbing &&
_buffering;
final track = widget.locked
? _inactiveTrack()
: source == null
@@ -166,7 +179,6 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
spriteAxisService: widget.spriteAxisService,
thumbnailsUrl: widget.thumbnailsUrl,
episodeId: widget.episodeId!,
posterUrl: widget.posterUrl,
position: previewPosition,
duration: video!.duration,
),
@@ -202,14 +214,24 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
void _syncBufferState({bool notify = true}) {
final source = widget.controller;
if (widget.locked || source == null) {
if (widget.locked || widget.suppressBufferLoading || source == null) {
_bufferTimer?.cancel();
_bufferTimer = null;
_lastPosition = null;
_setBuffering(false, notify: notify);
return;
}
final value = source.value;
if (!value.isInitialized) {
_bufferTimer?.cancel();
_bufferTimer = null;
_lastPosition = null;
_setBuffering(false, notify: notify);
return;
}
final previousPosition = _lastPosition;
_lastPosition = value.position;
if (previousPosition != null && value.position > previousPosition) {
_bufferTimer?.cancel();
_bufferTimer = null;
_setBuffering(false, notify: notify);
@@ -221,14 +243,22 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
_setBuffering(false, notify: notify);
return;
}
if (previousPosition == null &&
value.isPlaying &&
value.position > Duration.zero) {
_setBuffering(false, notify: notify);
return;
}
if (_buffering || _bufferTimer != null) return;
final bufferingPosition = value.position;
_bufferTimer = Timer(_bufferDebounce, () {
_bufferTimer = null;
final current = widget.controller;
if (!mounted ||
current != source ||
!current!.value.isInitialized ||
!current.value.isBuffering) {
!current.value.isBuffering ||
current.value.position != bufferingPosition) {
return;
}
_setBuffering(true);
@@ -340,10 +370,8 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
children: [
Align(
alignment: Alignment.centerLeft,
child: AnimatedContainer(
child: Container(
key: const Key('home-feed-progress-track'),
duration: _trackResizeDuration,
curve: Curves.easeOut,
width: width,
height: trackHeight,
color: AppColors.border,
@@ -351,10 +379,8 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
),
Align(
alignment: Alignment.centerLeft,
child: AnimatedContainer(
child: Container(
key: const Key('home-feed-progress-played'),
duration: dragging ? Duration.zero : _trackResizeDuration,
curve: Curves.easeOut,
width: playedWidth,
height: trackHeight,
color: AppColors.blue,
@@ -370,10 +396,8 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
child: SizedBox.square(
dimension: _thumbActiveSize,
child: Center(
child: AnimatedContainer(
child: Container(
key: const Key('home-feed-progress-thumb'),
duration: _trackResizeDuration,
curve: Curves.easeOut,
width: size,
height: size,
decoration: const BoxDecoration(
@@ -1,28 +1,31 @@
// Author: fruit.com.cn
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/formatting/count_format.dart';
import '../../../core/formatting/localized_content.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
import 'interaction_rail.dart';
const double _seriesFont = 19;
const double _tagFont = 13;
const double _synopsisFont = 13;
const double _seriesFont = 21;
const double _tagFont = 14;
const double _synopsisFont = 15;
const double _watchAllHeight = 44;
const double _actionGap = 28;
const double _actionIcon = 32;
const double _actionWidth = 64;
const List<Shadow> _textShadows = [
Shadow(color: AppColors.shadow, blurRadius: 6, offset: Offset(0, 1)),
];
final RegExp _tagSplitter = RegExp(r'[,/、·]');
/// 通栏「观看完整剧集」半透明白底条高度,overlay 用它安排底部避让。
const double homeFeedWatchAllHeight = _watchAllHeight;
/// 播放量紧凑展示(跟随语言):zh 20万 / en 200K / id 200 rb。
String _compactViewers(int count, Locale locale) =>
NumberFormat.compact(locale: locale.languageCode).format(count);
class HomeFeedInfoPanel extends StatefulWidget {
const HomeFeedInfoPanel({
super.key,
@@ -30,6 +33,7 @@ class HomeFeedInfoPanel extends StatefulWidget {
required this.episode,
required this.onDetail,
required this.onOpenFullPlayer,
this.onOpenSearch,
});
final Drama drama;
@@ -37,6 +41,9 @@ class HomeFeedInfoPanel extends StatefulWidget {
final VoidCallback onDetail;
final VoidCallback onOpenFullPlayer;
/// 热搜胶囊点击;为空或播放量为 0 时不显示胶囊。
final VoidCallback? onOpenSearch;
@override
State<HomeFeedInfoPanel> createState() => _HomeFeedInfoPanelState();
}
@@ -51,9 +58,22 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
final synopsis = localizedDramaSynopsis(l10n, widget.drama).trim();
final genres = _genreValues(Localizations.localeOf(context).languageCode);
return Column(
key: const Key('home-feed-info-panel'),
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.onOpenSearch != null && widget.drama.viewCount > 0) ...[
_HotSearchPill(
label: l10n.feedWatchingCount(
_compactViewers(
widget.drama.viewCount,
Localizations.localeOf(context),
),
),
onTap: widget.onOpenSearch!,
),
const SizedBox(height: 8),
],
GestureDetector(
key: const Key('home-feed-series-name'),
behavior: HitTestBehavior.opaque,
@@ -70,12 +90,12 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: _seriesFont,
fontWeight: FontWeight.w600,
fontWeight: FontWeight.w700,
shadows: _textShadows,
),
),
),
const SizedBox(width: 4),
const SizedBox(width: 2),
const Icon(
Icons.chevron_right_rounded,
size: 20,
@@ -84,119 +104,96 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
],
),
),
const SizedBox(height: 8),
const SizedBox(height: 6),
_tagMetaRow(l10n, genres),
if (synopsis.isNotEmpty) ...[
const SizedBox(height: 8),
_synopsis(l10n, synopsis),
],
const SizedBox(height: 12),
_watchAll(context, l10n),
],
);
}
Widget _tagMetaRow(AppLocalizations l10n, List<String> genres) {
return Row(
final chips = <Widget>[
if (isHotDrama(widget.drama))
_TagChip(
key: const Key('home-feed-hot-badge'),
label: l10n.homeBadgeHot,
filled: true,
),
for (final genre in genres)
_TagChip(key: Key('home-feed-tag-$genre'), label: genre),
];
return SizedBox(
key: const Key('home-feed-tags'),
children: [
if (isHotDrama(widget.drama)) ...[
Container(
key: const Key('home-feed-hot-badge'),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: AppColors.error,
borderRadius: BorderRadius.circular(3),
),
child: Text(
l10n.homeBadgeHot,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(width: 8),
],
Flexible(
fit: FlexFit.loose,
child: Text(
genres.join(' '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.overlayLabel,
fontSize: _tagFont,
),
),
),
const SizedBox(width: 8),
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,
),
),
),
],
height: 25,
child: ListView.separated(
scrollDirection: Axis.horizontal,
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: chips.length,
separatorBuilder: (_, _) => const SizedBox(width: 8),
itemBuilder: (_, index) => chips[index],
),
);
}
Widget _synopsis(AppLocalizations l10n, String synopsis) {
const style = TextStyle(
color: AppColors.overlaySecondary,
final prefix = l10n.feedEpisodePrefix(widget.episode.number);
final baseStyle = const TextStyle(
color: AppColors.textPrimary,
fontSize: _synopsisFont,
height: 1.35,
height: 1.3,
shadows: _textShadows,
);
final span = TextSpan(
children: [
TextSpan(
text: prefix,
style: baseStyle.copyWith(fontWeight: FontWeight.w600),
),
TextSpan(text: synopsis, style: baseStyle),
],
);
if (_synopsisExpanded) {
return _expandedSynopsis(span, baseStyle, l10n);
}
return LayoutBuilder(
builder: (context, constraints) {
final toggle = _synopsisToggle(
key: const Key('home-feed-synopsis-more'),
label: l10n.expandSynopsis,
);
final painter = TextPainter(
text: TextSpan(text: synopsis, style: style),
maxLines: 2,
text: span,
maxLines: 1,
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout(maxWidth: constraints.maxWidth);
final overflows = painter.didExceedMaxLines;
if (!overflows) {
return Text(
synopsis,
if (!painter.didExceedMaxLines) {
return Text.rich(
span,
key: const Key('home-feed-synopsis'),
style: style,
maxLines: 1,
style: baseStyle,
);
}
if (_synopsisExpanded) {
return _expandedSynopsis(constraints.maxWidth, synopsis, style, l10n);
}
return Stack(
// 设计稿:单行省略号 + 行内固定「展开」。
return Row(
key: const Key('home-feed-synopsis-collapsed'),
children: [
Padding(
padding: const EdgeInsets.only(right: 40),
child: Text(
synopsis,
Expanded(
child: Text.rich(
span,
key: const Key('home-feed-synopsis'),
maxLines: 2,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: style,
),
),
Positioned(
right: 0,
bottom: 0,
child: _synopsisToggle(
key: const Key('home-feed-synopsis-more'),
label: l10n.expandSynopsis,
style: baseStyle,
),
),
const SizedBox(width: 2),
toggle,
],
);
},
@@ -204,26 +201,28 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
}
Widget _expandedSynopsis(
double maxWidth,
String synopsis,
InlineSpan span,
TextStyle style,
AppLocalizations l10n,
) {
return SizedBox(
width: maxWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(synopsis, key: const Key('home-feed-synopsis'), style: style),
Align(
alignment: Alignment.centerRight,
child: _synopsisToggle(
key: const Key('home-feed-synopsis-more'),
label: l10n.showLess,
),
return Column(
key: const Key('home-feed-synopsis-expanded'),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text.rich(
span,
key: const Key('home-feed-synopsis'),
style: style,
),
const SizedBox(height: 2),
Align(
alignment: Alignment.centerRight,
child: _synopsisToggle(
key: const Key('home-feed-synopsis-more'),
label: l10n.showLess,
),
],
),
),
],
);
}
@@ -237,54 +236,12 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
color: AppColors.textPrimary,
fontSize: _synopsisFont,
fontWeight: FontWeight.w600,
shadows: _textShadows,
),
),
);
}
Widget _watchAll(BuildContext context, AppLocalizations l10n) {
final screenWidth = MediaQuery.sizeOf(context).width;
return LayoutBuilder(
builder: (context, constraints) {
final buttonWidth = math.min(screenWidth * 0.7, constraints.maxWidth);
return Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: buttonWidth,
height: _watchAllHeight,
child: DecoratedBox(
key: const Key('home-feed-full-series-bg'),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [AppColors.actionRed, AppColors.blue],
),
borderRadius: BorderRadius.circular(8),
),
child: Material(
color: AppColors.transparent,
child: InkWell(
key: const Key('home-feed-full-series'),
onTap: widget.onOpenFullPlayer,
borderRadius: BorderRadius.circular(8),
child: Center(
child: Text(
l10n.homeWatchAll,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
),
),
),
);
},
);
}
List<String> _genreValues(String languageCode) {
final localized = widget.drama.localizedTypeLabels(languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
@@ -300,6 +257,147 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
}
}
/// 热搜榜降级胶囊:🔍 共 xxx 人在看 ›(暂无榜单接口,点击跳搜索页)。
class _HotSearchPill extends StatelessWidget {
const _HotSearchPill({required this.label, required this.onTap});
final String label;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return GestureDetector(
key: const Key('home-feed-hot-search-pill'),
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: AppColors.textPrimary.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.search_rounded,
size: 15,
color: AppColors.textPrimary,
),
const SizedBox(width: 5),
Text(
label,
maxLines: 1,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const SizedBox(width: 2),
const Icon(
Icons.chevron_right_rounded,
size: 16,
color: AppColors.textPrimary,
),
],
),
),
);
}
}
/// 热剧红胶囊 / 类型深色半透明填充胶囊。
class _TagChip extends StatelessWidget {
const _TagChip({super.key, required this.label, this.filled = false});
final String label;
final bool filled;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
alignment: Alignment.center,
decoration: BoxDecoration(
color: filled
? AppColors.brandRed
: AppColors.textPrimary.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(4),
),
child: Text(
label,
maxLines: 1,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: _tagFont,
fontWeight: FontWeight.w500,
height: 1.2,
shadows: _textShadows,
),
),
);
}
}
/// 底部通栏条:🎬 观看完整剧集 全 N 集。
class HomeFeedWatchAllBar extends StatelessWidget {
const HomeFeedWatchAllBar({
super.key,
required this.drama,
required this.onTap,
});
final Drama drama;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Material(
key: const Key('home-feed-full-series-bg'),
color: AppColors.textPrimary.withValues(alpha: 0.15),
child: InkWell(
key: const Key('home-feed-full-series'),
onTap: onTap,
child: SizedBox(
height: _watchAllHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: [
const Icon(
Icons.movie_rounded,
size: 22,
color: AppColors.onPrimary,
),
const SizedBox(width: 10),
Expanded(
child: Text(
l10n.watchFullSeries('${drama.episodeCount}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 15,
fontWeight: FontWeight.w500,
),
),
),
const Icon(
Icons.chevron_right_rounded,
size: 22,
color: AppColors.textPrimary,
),
],
),
),
),
),
);
}
}
class HomeFeedActionRail extends StatelessWidget {
const HomeFeedActionRail({
super.key,
@@ -307,112 +405,70 @@ class HomeFeedActionRail extends StatelessWidget {
required this.liked,
required this.onSave,
required this.onLike,
required this.onEpisodes,
required this.onComments,
required this.onShare,
this.favoriteCount,
this.likeCount,
this.commentCount,
});
final bool saved;
final bool liked;
final int? favoriteCount;
final int? likeCount;
final int? commentCount;
final VoidCallback onSave;
final VoidCallback onLike;
final VoidCallback onEpisodes;
final VoidCallback onComments;
final VoidCallback onShare;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return SizedBox(
width: _actionWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_action(
key: const Key('rail-save'),
icon: saved
? Icons.bookmark_rounded
: Icons.bookmark_border_rounded,
label: favoriteCount == null
? l10n.favorite
: formatInteractionCount(favoriteCount!),
labelKey: const Key('rail-save-count'),
onTap: onSave,
),
const SizedBox(height: _actionGap),
_action(
key: const Key('rail-like'),
icon: liked
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
iconColor: liked
? AppColors.doubleTapHeartRed
: AppColors.textPrimary,
label: likeCount == null
? l10n.like
: formatInteractionCount(likeCount!),
labelKey: const Key('rail-like-count'),
onTap: onLike,
),
const SizedBox(height: _actionGap),
_action(
key: const Key('rail-episodes'),
icon: Icons.layers_rounded,
label: l10n.episodes,
labelKey: const Key('rail-episodes-label'),
labelFontSize: 11,
onTap: onEpisodes,
),
],
),
);
}
Widget _action({
required Key key,
required IconData icon,
required String label,
required Key labelKey,
required VoidCallback onTap,
Color iconColor = AppColors.textPrimary,
double labelFontSize = 12,
}) {
return GestureDetector(
key: key,
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
size: _actionIcon,
color: iconColor,
shadows: const [
Shadow(
color: AppColors.shadowSoft,
blurRadius: 4,
offset: Offset(0, 1),
),
],
),
const SizedBox(height: 2),
Text(
label,
key: labelKey,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(
color: AppColors.textPrimary,
fontSize: labelFontSize,
fontWeight: FontWeight.w500,
height: 1,
shadows: _textShadows,
),
),
],
),
return InteractionRail(
itemGap: 18,
buttonSize: 48,
iconSize: 36,
countFontSize: 15,
iconCountGap: 6,
items: [
InteractionRailItem(
key: const Key('rail-save'),
asset: 'assets/icon/rail/rail_save.png',
label: l10n.favorite,
count: favoriteCount,
countKey: const Key('rail-save-count'),
selected: saved,
selectedColor: AppColors.brandRed,
onTap: onSave,
),
InteractionRailItem(
key: const Key('rail-comments'),
asset: 'assets/icon/rail/rail_comment.png',
label: l10n.comments,
count: commentCount,
countKey: const Key('rail-comments-count'),
onTap: onComments,
),
InteractionRailItem(
key: const Key('rail-like'),
asset: 'assets/icon/rail/rail_like.png',
label: l10n.like,
count: likeCount,
countKey: const Key('rail-like-count'),
selected: liked,
selectedColor: AppColors.brandRed,
onTap: onLike,
),
InteractionRailItem(
key: const Key('rail-share'),
icon: Icons.reply_rounded,
mirrorIcon: true,
label: l10n.share,
countKey: const Key('rail-share-label'),
onTap: onShare,
),
],
);
}
}
+68 -23
View File
@@ -5,38 +5,59 @@ import 'package:flutter/material.dart';
import '../../../core/formatting/count_format.dart';
import '../../../core/theme/app_colors.dart';
const double _buttonSize = 44;
const double _iconSize = 32;
const double _itemGap = 24;
const double _defaultButtonSize = 44;
const double _defaultIconSize = 32;
const double _defaultCountFont = 12;
const double _defaultIconCountGap = 2;
const double _defaultItemGap = 24;
/// 互动栏单项:图标、计数与点击。
class InteractionRailItem {
const InteractionRailItem({
required this.key,
required this.asset,
required this.label,
required this.onTap,
this.asset,
this.icon,
this.count,
this.countKey,
this.selected = false,
this.selectedColor = AppColors.blue,
});
this.mirrorIcon = false,
}) : assert((asset == null) != (icon == null));
final Key key;
final String asset;
final String? asset;
final IconData? icon;
final String label;
final VoidCallback onTap;
final int? count;
final Key? countKey;
final bool selected;
final Color selectedColor;
/// 水平镜像图标(分享弯箭头用 reply 镜像得到)。
final bool mirrorIcon;
}
/// 播放页与首页 feed 共用的右侧互动栏:收藏/评论/喜欢/分享。
class InteractionRail extends StatelessWidget {
const InteractionRail({super.key, required this.items});
const InteractionRail({
super.key,
required this.items,
this.itemGap = _defaultItemGap,
this.buttonSize = _defaultButtonSize,
this.iconSize = _defaultIconSize,
this.countFontSize = _defaultCountFont,
this.iconCountGap = _defaultIconCountGap,
});
final List<InteractionRailItem> items;
final double itemGap;
final double buttonSize;
final double iconSize;
final double countFontSize;
final double iconCountGap;
@override
Widget build(BuildContext context) {
@@ -44,8 +65,14 @@ class InteractionRail extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
for (var index = 0; index < items.length; index++) ...[
if (index > 0) const SizedBox(height: _itemGap),
_RailButton(item: items[index]),
if (index > 0) SizedBox(height: itemGap),
_RailButton(
item: items[index],
buttonSize: buttonSize,
iconSize: iconSize,
countFontSize: countFontSize,
iconCountGap: iconCountGap,
),
],
],
);
@@ -53,43 +80,61 @@ class InteractionRail extends StatelessWidget {
}
class _RailButton extends StatelessWidget {
const _RailButton({required this.item});
const _RailButton({
required this.item,
required this.buttonSize,
required this.iconSize,
required this.countFontSize,
required this.iconCountGap,
});
final InteractionRailItem item;
final double buttonSize;
final double iconSize;
final double countFontSize;
final double iconCountGap;
@override
Widget build(BuildContext context) {
final tint = item.selected ? item.selectedColor : AppColors.onPrimary;
return Column(
key: item.key,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox.square(
dimension: _buttonSize,
dimension: buttonSize,
child: IconButton(
onPressed: item.onTap,
padding: EdgeInsets.zero,
icon: Image.asset(
item.asset,
width: _iconSize,
height: _iconSize,
fit: BoxFit.contain,
color: item.selected ? item.selectedColor : AppColors.onPrimary,
colorBlendMode: BlendMode.srcIn,
),
icon: item.asset != null
? Image.asset(
item.asset!,
width: iconSize,
height: iconSize,
fit: BoxFit.contain,
color: tint,
colorBlendMode: BlendMode.srcIn,
)
: Transform.flip(
flipX: item.mirrorIcon,
child: Icon(item.icon, size: iconSize, color: tint),
),
),
),
const SizedBox(height: 2),
SizedBox(height: iconCountGap),
Text(
item.count == null ? item.label : formatInteractionCount(item.count!),
key: item.countKey,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
style: TextStyle(
color: AppColors.onPrimary,
height: 1,
fontSize: 12,
fontSize: countFontSize,
fontWeight: FontWeight.w600,
shadows: [Shadow(blurRadius: 6, color: AppColors.mediaBlack)],
shadows: const [
Shadow(blurRadius: 6, color: AppColors.mediaBlack),
],
),
),
],
@@ -1,13 +1,16 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
const int _heartDurationMs = 680;
const int _heartDurationMs = 1500;
const double _heartPopPortion = 0.18;
const double _heartStartScale = 0.7;
const double _heartHoldPortion = 0.45;
const double _heartHoldPortion = 0.55;
const List<_HeartParticle> _hearts = [
_HeartParticle(
@@ -35,75 +38,136 @@ const List<_HeartParticle> _hearts = [
/// 双击点赞时,在点击位置飘出一小簇心。
class PlayerDoubleTapHeartBurst extends StatefulWidget {
const PlayerDoubleTapHeartBurst({super.key, required this.onCompleted});
const PlayerDoubleTapHeartBurst({
super.key,
required this.burstId,
required this.onCompleted,
this.origin = Offset.zero,
this.now,
});
final int burstId;
final VoidCallback onCompleted;
final Offset origin;
final DateTime Function()? now;
@override
State<PlayerDoubleTapHeartBurst> createState() =>
_PlayerDoubleTapHeartBurstState();
}
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst> {
Timer? _timer;
late final DateTime _startAt;
late final int _totalMs;
final Stopwatch _lifetime = Stopwatch();
int _elapsedMs = 0;
int _tickCount = 0;
bool _completed = false;
@override
void initState() {
super.initState();
final total = _hearts
_lifetime.start();
_startAt = _now();
_totalMs = _hearts
.map((heart) => heart.delay + _heartDurationMs)
.reduce((left, right) => left > right ? left : right);
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: total),
)..addStatusListener(_onStatus);
_controller.forward();
if (kDebugMode) {
debugPrint(
'[player] phase=heart-burst-start '
'id=${widget.burstId} count=${_hearts.length} '
'configuredMs=$_totalMs at=${widget.origin.dx.toStringAsFixed(1)},'
'${widget.origin.dy.toStringAsFixed(1)}',
);
}
_timer = Timer.periodic(
const Duration(milliseconds: 16),
(_) => _handleTick(),
);
}
void _onStatus(AnimationStatus status) {
if (status != AnimationStatus.completed || _completed) return;
DateTime _now() => widget.now?.call() ?? DateTime.now();
void _handleTick() {
if (!mounted || _completed) return;
final rawElapsedMs = _now().difference(_startAt).inMilliseconds;
final elapsedMs = rawElapsedMs < 0
? 0
: rawElapsedMs > _totalMs
? _totalMs
: rawElapsedMs;
_elapsedMs = elapsedMs;
_tickCount++;
if (kDebugMode && _tickCount % 10 == 0) {
debugPrint(
'[player] phase=heart-tick id=${widget.burstId} '
'elapsedMs=$_elapsedMs',
);
}
if (_elapsedMs >= _totalMs) {
_complete();
return;
}
setState(() {});
}
void _complete() {
if (_completed) return;
_completed = true;
_timer?.cancel();
if (kDebugMode) {
debugPrint(
'[player] phase=heart-burst-complete '
'id=${widget.burstId} '
'configuredMs=$_totalMs',
);
}
widget.onCompleted();
}
@override
void dispose() {
_controller
..removeStatusListener(_onStatus)
..dispose();
if (kDebugMode) {
final elapsedMs = _completed ? _totalMs : _elapsedMs;
debugPrint(
'[player] phase=heart-burst-dispose '
'id=${widget.burstId} elapsedMs=$elapsedMs '
'completed=${_completed ? 1 : 0}',
);
if (!_completed) {
debugPrintStack(
maxFrames: 30,
label:
'[player] heart-burst-premature-dispose '
'id=${widget.burstId} mount=root-overlay',
);
}
}
_lifetime.stop();
_timer?.cancel();
_timer = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
return IgnorePointer(
child: SizedBox.shrink(
child: AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final elapsed =
_controller.value * _controller.duration!.inMilliseconds;
return Stack(
clipBehavior: Clip.none,
children: [
for (var index = 0; index < _hearts.length; index++)
_heart(_hearts[index], elapsed, index),
],
);
},
),
child: Stack(
fit: StackFit.expand,
clipBehavior: Clip.none,
children: [
for (var index = 0; index < _hearts.length; index++)
_heart(_hearts[index], _elapsedMs.toDouble(), index),
],
),
);
}
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 rawProgress = (elapsed - heart.delay) / _heartDurationMs;
if (rawProgress < 0) return const SizedBox.shrink();
final progress = rawProgress.clamp(0.0, 1.0);
final move = Curves.easeOutCubic.transform(progress);
final scale = progress < _heartPopPortion
? _heartStartScale +
@@ -113,8 +177,8 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
? 1.0
: 1 - ((progress - _heartHoldPortion) / (1 - _heartHoldPortion));
return Positioned(
left: heart.drift * move - heart.size / 2,
top: -heart.size / 2 - heart.travel * move,
left: widget.origin.dx + heart.drift * move - heart.size / 2,
top: widget.origin.dy - heart.size / 2 - heart.travel * move,
child: Opacity(
opacity: opacity.clamp(0.0, 1.0),
child: Transform.scale(
@@ -0,0 +1,52 @@
// Author: fruit.com.cn
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
/// Tracks heart overlays for the lifetime of one player page.
class PlayerHeartOverlayController {
final Map<int, OverlayEntry> _entries = {};
void track(int id, OverlayEntry entry) {
_entries[id] = entry;
}
void untrack(int id) {
_entries.remove(id);
}
void dispose() {
for (final entry in _entries.entries.toList()) {
if (entry.value.mounted) entry.value.remove();
entry.value.dispose();
if (kDebugMode) {
debugPrint(
'[player] phase=heart-burst-entry-removed '
'id=${entry.key} reason=page-dispose',
);
}
}
_entries.clear();
}
}
class PlayerHeartOverlayScope extends InheritedWidget {
const PlayerHeartOverlayScope({
super.key,
required this.controller,
required super.child,
});
final PlayerHeartOverlayController controller;
static PlayerHeartOverlayController? maybeOf(BuildContext context) {
return context
.dependOnInheritedWidgetOfExactType<PlayerHeartOverlayScope>()
?.controller;
}
@override
bool updateShouldNotify(PlayerHeartOverlayScope oldWidget) {
return controller != oldWidget.controller;
}
}
@@ -0,0 +1,45 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
class PlayerLoadingOverlay extends StatelessWidget {
const PlayerLoadingOverlay({
super.key,
required this.opacity,
required this.onFadeEnd,
});
final double opacity;
final VoidCallback onFadeEnd;
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
opacity: opacity,
duration: const Duration(milliseconds: 140),
curve: Curves.easeOut,
onEnd: onFadeEnd,
child: Container(
key: const Key('player-loading-surface'),
width: AppDimens.refreshIndicatorSize,
height: AppDimens.refreshIndicatorSize,
decoration: BoxDecoration(
color: AppColors.refreshIndicatorSurface,
borderRadius: BorderRadius.circular(AppDimens.refreshIndicatorRadius),
),
alignment: Alignment.center,
child: const SizedBox.square(
dimension: AppDimens.refreshSpinnerSize,
child: CircularProgressIndicator(
key: Key('player-entry-loading'),
color: Colors.white,
strokeWidth: AppDimens.refreshSpinnerStroke,
),
),
),
);
}
}
+129 -119
View File
@@ -1,167 +1,177 @@
// Author: fruit.com.cn
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../../../core/config/app_config.dart';
import '../../../core/data/services/sprite_thumbnail_asset_loader.dart';
import '../../../core/data/services/sprite_thumbnail_axis.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/remote_image.dart';
import 'scrub_preview_card.dart';
/// 无雪碧图地址时不垫帧,交还给纯黑底。
Widget? playerOpeningFrame(String? thumbnailsUrl) {
final url = thumbnailsUrl?.trim() ?? '';
if (url.isEmpty) return null;
return PlayerOpeningFrame(thumbnailsUrl: url);
enum PlayerOpeningFallback { handoff, poster, thumbnails, black }
PlayerOpeningFallback playerOpeningFallback({
String? posterUrl,
String? thumbnailsUrl,
}) {
if (posterUrl?.trim().isNotEmpty ?? false) {
return PlayerOpeningFallback.poster;
}
if (thumbnailsUrl?.trim().isNotEmpty ?? false) {
return PlayerOpeningFallback.thumbnails;
}
return PlayerOpeningFallback.black;
}
/// 解码出视频画面前,用本集雪碧图第一帧垫底。
/// 当前集首帧在视频纹理未就绪时占位;空地址交还纯黑底。
Widget? playerOpeningFrame(
String? thumbnailsUrl, {
String? posterUrl,
required SpriteThumbnailAxisSource spriteSource,
BoxFit fit = BoxFit.cover,
}) {
final thumbnails = thumbnailsUrl?.trim() ?? '';
final poster = posterUrl?.trim() ?? '';
if (playerOpeningFallback(posterUrl: poster, thumbnailsUrl: thumbnails) ==
PlayerOpeningFallback.black) {
return null;
}
return PlayerOpeningFrame(
thumbnailsUrl: thumbnails,
posterUrl: poster,
spriteSource: spriteSource,
fit: fit,
);
}
/// 与视频共用全屏父约束和 BoxFit,切换时保持相同可见区域。
class PlayerOpeningFrame extends StatefulWidget {
const PlayerOpeningFrame({
super.key,
required this.thumbnailsUrl,
this.loader,
this.cache,
required this.spriteSource,
this.posterUrl,
this.fit = BoxFit.cover,
});
/// 当前视频原始分辨率首帧地址,优先于雪碧图。
final String? posterUrl;
/// 当前视频雪碧图 WebVTT 地址。
final String thumbnailsUrl;
final SpriteThumbnailAssetLoader? loader;
final OpeningFrameCache? cache;
/// 进度条拖动预览共用的雪碧图时间轴与解码缓存。
final SpriteThumbnailAxisSource spriteSource;
/// 必须与同页视频层使用相同适配规则。
final BoxFit fit;
@override
State<PlayerOpeningFrame> createState() => _PlayerOpeningFrameState();
}
class _PlayerOpeningFrameState extends State<PlayerOpeningFrame> {
SpriteThumbnailFrame? _frame;
int _serial = 0;
bool _posterFailed = false;
@override
void initState() {
super.initState();
unawaited(_load());
widget.spriteSource.addListener(_handleSpriteChanged);
_prepareSpriteIfNeeded();
}
@override
void didUpdateWidget(covariant PlayerOpeningFrame oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.thumbnailsUrl != widget.thumbnailsUrl) {
_frame = null;
unawaited(_load());
if (oldWidget.posterUrl != widget.posterUrl) {
_posterFailed = false;
}
if (oldWidget.spriteSource != widget.spriteSource) {
oldWidget.spriteSource.removeListener(_handleSpriteChanged);
widget.spriteSource.addListener(_handleSpriteChanged);
_prepareSpriteIfNeeded();
}
if (oldWidget.posterUrl != widget.posterUrl ||
oldWidget.thumbnailsUrl != widget.thumbnailsUrl) {
_prepareSpriteIfNeeded();
}
}
Future<void> _load() async {
final serial = ++_serial;
final frame = await (widget.cache ?? OpeningFrameCache.shared).load(
widget.thumbnailsUrl,
loader: widget.loader,
);
if (!mounted || serial != _serial) return;
setState(() => _frame = frame);
@override
void dispose() {
widget.spriteSource.removeListener(_handleSpriteChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
final frame = _frame;
void _handleSpriteChanged() {
if (mounted) setState(() {});
}
bool get _hasPoster =>
!_posterFailed && (widget.posterUrl?.trim().isNotEmpty ?? false);
void _prepareSpriteIfNeeded() {
if (_hasPoster || widget.thumbnailsUrl.trim().isEmpty) return;
unawaited(
widget.spriteSource.prepareAt(widget.thumbnailsUrl, Duration.zero),
);
}
Widget _handlePosterError() {
if (!_posterFailed) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _posterFailed) return;
setState(() => _posterFailed = true);
_prepareSpriteIfNeeded();
});
}
return _spriteOrBlack();
}
Widget _spriteOrBlack() {
final frame = widget.spriteSource.cachedFrameAt(
widget.thumbnailsUrl,
Duration.zero,
);
if (frame == null) return const SizedBox.expand();
return SpriteCropPreview(
key: const Key('player-opening-sprite'),
image: frame.image,
sourceRect: frame.sourceRect,
);
}
}
/// 相邻页共用的雪碧图首帧缓存,避免每页重复拉 VTT。
class OpeningFrameCache {
OpeningFrameCache({this.capacity = 6});
static final OpeningFrameCache shared = OpeningFrameCache();
final int capacity;
final Map<String, SpriteThumbnailFrame> _frames = {};
final Map<String, Future<SpriteThumbnailFrame?>> _loads = {};
/// 取 [thumbnailsUrl] 对应的第一帧;失败返回 null。
Future<SpriteThumbnailFrame?> load(
String? thumbnailsUrl, {
SpriteThumbnailAssetLoader? loader,
}) {
final url = _normalize(thumbnailsUrl);
if (url == null) return Future<SpriteThumbnailFrame?>.value();
final cached = _frames[url];
if (cached != null) return Future.value(cached);
return _loads.putIfAbsent(url, () => _fetch(url, loader));
}
Future<SpriteThumbnailFrame?> _fetch(
String url,
SpriteThumbnailAssetLoader? loader,
) async {
try {
final asset = loader ?? DioSpriteThumbnailAssetLoader();
final text = await asset.loadVtt(Uri.parse(url));
if (text == null || text.isEmpty) return null;
final axis = parseSpriteThumbnailVtt(text, vttUrl: url);
final cue = axis.cues.isEmpty ? null : axis.cues.first;
if (cue == null) return null;
final decoded = await asset.loadSprite(
axis.resolveSpriteUri(cue.spriteFile),
);
if (decoded == null) return null;
final frame = SpriteThumbnailFrame(
image: decoded.image,
sourceRect: _scaledRect(decoded, cue.sourceRect),
spriteUrl: axis.resolveSpriteUri(cue.spriteFile).toString(),
cue: cue,
);
_store(url, frame);
return frame;
} catch (_) {
return null;
} finally {
_loads.remove(url);
}
}
void _store(String url, SpriteThumbnailFrame frame) {
_frames.remove(url);
_frames[url] = frame;
while (_frames.length > capacity) {
final oldest = _frames.keys.first;
_frames.remove(oldest)?.image.dispose();
}
}
ui.Rect _scaledRect(SpriteThumbnailDecodedImage decoded, ui.Rect source) {
if (decoded.originalWidth <= 0 || decoded.originalHeight <= 0) {
return source;
}
final scaleX = decoded.image.width / decoded.originalWidth;
final scaleY = decoded.image.height / decoded.originalHeight;
return ui.Rect.fromLTWH(
source.left * scaleX,
source.top * scaleY,
source.width * scaleX,
source.height * scaleY,
fit: widget.fit,
);
}
String? _normalize(String? raw) {
final value = AppConfig.mediaUrl(raw?.trim() ?? '');
if (value.isEmpty) return null;
return value;
}
/// 测试收尾时清空缓存。
void clear() {
for (final frame in _frames.values) {
frame.image.dispose();
}
_frames.clear();
_loads.clear();
}
@override
Widget build(BuildContext context) => Stack(
fit: StackFit.expand,
children: [
const ColoredBox(color: AppColors.mediaBlack),
if (_hasPoster)
LayoutBuilder(
builder: (context, constraints) {
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
return Image.network(
AppConfig.mediaUrl(widget.posterUrl!.trim()),
key: const Key('player-opening-poster'),
fit: widget.fit,
cacheWidth: resolveImageDecodePixels(
constraints.maxWidth,
pixelRatio,
),
cacheHeight: resolveImageDecodePixels(
constraints.maxHeight,
pixelRatio,
),
gaplessPlayback: true,
errorBuilder: (_, _, _) => _handlePosterError(),
);
},
)
else
_spriteOrBlack(),
],
);
}
+23 -19
View File
@@ -14,6 +14,7 @@ import '../../../l10n/app_localizations.dart';
import 'player_center_toggle.dart';
import 'interaction_rail.dart';
import 'player_overlay_models.dart';
import 'player_tap_gesture_region.dart';
import 'seek_progress_bar.dart';
part 'player_overlay_parts.dart';
@@ -36,6 +37,7 @@ class PlayerPlaybackOverlay extends StatelessWidget {
required this.actions,
required this.controlsVisible,
required this.scrubbing,
this.suppressProgressLoading = false,
});
/// 展示数据。
@@ -49,23 +51,24 @@ class PlayerPlaybackOverlay extends StatelessWidget {
/// 正在拖动进度条。拖动期间清屏,只留进度条。
final bool scrubbing;
final bool suppressProgressLoading;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: LayoutBuilder(
builder: (context, constraints) => GestureDetector(
key: const Key('player-video-tap'),
behavior: HitTestBehavior.opaque,
onTap: actions.onTogglePlay,
onLongPressStart: (details) =>
_handleLongPressStart(details, constraints.maxWidth),
onLongPressEnd: (_) => actions.onBoostEnd(),
onLongPressCancel: actions.onBoostEnd,
),
child: PlayerTapGestureRegion(
key: const ValueKey('player-tap-gesture-region'),
gestureKey: const Key('player-video-tap'),
enabled: !scrubbing,
doubleTapEnabled: !data.locked,
onSingleTap: actions.onTogglePlay,
onDoubleTapLike: actions.onDoubleTapLike,
onLongPressStart: _handleLongPressStart,
onInteractionEnd: actions.onBoostEnd,
),
),
_top(context),
@@ -175,14 +178,6 @@ class PlayerPlaybackOverlay extends StatelessWidget {
selected: data.saved,
onTap: actions.onSave,
),
InteractionRailItem(
key: const Key('player-rail-comments'),
asset: 'assets/icon/rail/rail_comment.png',
label: data.l10n.comments,
count: data.commentCount,
countKey: const Key('player-rail-comments-count'),
onTap: actions.onComments,
),
InteractionRailItem(
key: const Key('player-rail-like'),
asset: 'assets/icon/rail/rail_like.png',
@@ -193,6 +188,14 @@ class PlayerPlaybackOverlay extends StatelessWidget {
selectedColor: AppColors.doubleTapHeartRed,
onTap: actions.onLike,
),
InteractionRailItem(
key: const Key('player-rail-comments'),
asset: 'assets/icon/rail/rail_comment.png',
label: data.l10n.comments,
count: data.commentCount,
countKey: const Key('player-rail-comments-count'),
onTap: actions.onComments,
),
InteractionRailItem(
key: const Key('player-rail-share'),
asset: 'assets/icon/rail/rail_share.png',
@@ -303,8 +306,9 @@ class PlayerPlaybackOverlay extends StatelessWidget {
spriteAxisService: data.spriteAxisService,
thumbnailsUrl: data.episode.thumbnailsUrl,
episodeId: data.episode.id,
posterUrl: data.drama.posterUrl,
inactiveTrackColor: AppColors.inactiveTrack,
fallbackDuration: Duration(seconds: data.episode.durationSec),
suppressBufferLoading: suppressProgressLoading,
onScrubStart: actions.onScrubStart,
onScrubEnd: actions.onScrubEnd,
onSeek: actions.onSeek,
@@ -1,5 +1,7 @@
// Author: fruit.com.cn
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:video_player/video_player.dart';
@@ -87,6 +89,7 @@ class PlayerOverlayActions {
const PlayerOverlayActions({
required this.onBack,
required this.onTogglePlay,
this.onDoubleTapLike,
required this.onClear,
required this.onExitClear,
required this.onDetail,
@@ -111,6 +114,9 @@ class PlayerOverlayActions {
/// 切换播放状态。
final VoidCallback onTogglePlay;
/// 双击画面点赞;位置用于飘心。
final ValueChanged<Offset>? onDoubleTapLike;
/// 进入清屏。
final VoidCallback onClear;
@@ -0,0 +1,214 @@
// Author: fruit.com.cn
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import '../../../core/theme/app_colors.dart';
import 'player_opening_frame.dart';
import 'player_video_surface.dart';
enum PlayerRenderSlotRole { previous, current, next }
class PlayerRenderSlotData {
const PlayerRenderSlotData({
required this.role,
this.index,
this.pagePosition,
this.controller,
this.videoUrl = '',
this.theater = false,
this.placeholder,
this.warmFrameAvailable = false,
this.thumbnailReady = false,
this.posterReady = false,
this.fallback = PlayerOpeningFallback.black,
this.warmSlotReused = false,
this.waitForPlaybackFrame = false,
});
final PlayerRenderSlotRole role;
final int? index;
final double? pagePosition;
final VideoPlayerController? controller;
final String videoUrl;
final bool theater;
final Widget? placeholder;
final bool warmFrameAvailable;
final bool thumbnailReady;
final bool posterReady;
final PlayerOpeningFallback fallback;
final bool warmSlotReused;
final bool waitForPlaybackFrame;
factory PlayerRenderSlotData.empty(PlayerRenderSlotRole role) {
return PlayerRenderSlotData(role: role);
}
}
/// 播放画面不随 PageView 生命周期销毁,三个固定槽位只更新控制器和位置。
class PlayerRenderStack extends StatefulWidget {
const PlayerRenderStack({
super.key,
required this.pageController,
required this.slots,
this.onCurrentVideoVisible,
});
final PageController pageController;
final Map<PlayerRenderSlotRole, PlayerRenderSlotData> slots;
final ValueChanged<int?>? onCurrentVideoVisible;
@override
State<PlayerRenderStack> createState() => _PlayerRenderStackState();
}
class _PlayerRenderStackState extends State<PlayerRenderStack> {
int? _lastCurrentIndex;
@override
void initState() {
super.initState();
_lastCurrentIndex = _currentSlot.index;
_log(
'init current=${_lastCurrentIndex ?? '-'} '
'pageController=${identityHashCode(widget.pageController)}',
);
}
@override
void didUpdateWidget(covariant PlayerRenderStack oldWidget) {
super.didUpdateWidget(oldWidget);
final currentIndex = _currentSlot.index;
if (_lastCurrentIndex != currentIndex) {
_log(
'session-index previous=${_lastCurrentIndex ?? '-'} '
'current=${currentIndex ?? '-'}',
);
_lastCurrentIndex = currentIndex;
}
}
@override
void dispose() {
_log(
'dispose current=${_lastCurrentIndex ?? '-'} '
'pageController=${identityHashCode(widget.pageController)}',
);
super.dispose();
}
PlayerRenderSlotData get _currentSlot =>
widget.slots[PlayerRenderSlotRole.current] ??
PlayerRenderSlotData.empty(PlayerRenderSlotRole.current);
@override
Widget build(BuildContext context) {
return IgnorePointer(
child: AnimatedBuilder(
animation: widget.pageController,
builder: (context, _) {
return LayoutBuilder(
builder: (context, constraints) {
final viewportHeight = constraints.maxHeight.isFinite
? constraints.maxHeight
: MediaQuery.sizeOf(context).height;
final pageOffset = _pageOffset();
final currentPage = _currentSlot.pagePosition ?? pageOffset;
final slots = [
_slotData(PlayerRenderSlotRole.previous),
_slotData(PlayerRenderSlotRole.current),
_slotData(PlayerRenderSlotRole.next),
];
return Stack(
key: const Key('player-render-stack'),
fit: StackFit.expand,
clipBehavior: Clip.hardEdge,
children: [
const ColoredBox(
key: Key('player-fallback-background'),
color: AppColors.mediaBlack,
),
for (final slot in slots)
_positionedSurface(
slot,
pageOffset: pageOffset,
viewportHeight: viewportHeight,
fallbackPage: _fallbackPage(slot.role, currentPage),
),
],
);
},
);
},
),
);
}
PlayerRenderSlotData _slotData(PlayerRenderSlotRole role) {
return widget.slots[role] ?? PlayerRenderSlotData.empty(role);
}
double _pageOffset() {
if (!widget.pageController.hasClients) {
return widget.pageController.initialPage.toDouble();
}
final position = widget.pageController.position;
if (!position.hasPixels ||
!position.hasViewportDimension ||
position.viewportDimension <= 0) {
return widget.pageController.initialPage.toDouble();
}
return position.pixels / position.viewportDimension;
}
double _fallbackPage(PlayerRenderSlotRole role, double currentPage) {
return switch (role) {
PlayerRenderSlotRole.previous => currentPage - 1,
PlayerRenderSlotRole.current => currentPage,
PlayerRenderSlotRole.next => currentPage + 1,
};
}
Widget _positionedSurface(
PlayerRenderSlotData slot, {
required double pageOffset,
required double viewportHeight,
required double fallbackPage,
}) {
final slotPage = slot.pagePosition ?? fallbackPage;
final offset = (slotPage - pageOffset) * viewportHeight;
return Positioned.fill(
child: Transform.translate(
key: Key('player-render-transform-${slot.role.name}'),
offset: Offset(0, offset),
child: PlayerVideoSurface(
key: ValueKey('player-render-slot-${slot.role.name}'),
debugSlot: slot.role.name,
debugIndex: slot.index,
showFallbackBackground: false,
controller: slot.controller,
videoUrl: slot.videoUrl,
theater: slot.theater,
placeholder: slot.placeholder,
warmFrameAvailable: slot.warmFrameAvailable,
thumbnailReady: slot.thumbnailReady,
posterReady: slot.posterReady,
fallback: slot.fallback,
warmSlotReused: slot.warmSlotReused,
waitForPlaybackFrame: slot.waitForPlaybackFrame,
onVideoVisible: slot.role == PlayerRenderSlotRole.current
? () => widget.onCurrentVideoVisible?.call(slot.index)
: null,
),
),
);
}
void _log(String message) {
if (!kDebugMode) return;
debugPrint(
'[player-render] ts=${DateTime.now().millisecondsSinceEpoch} $message',
);
}
}
@@ -0,0 +1,196 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'player_double_tap_hearts.dart';
import 'player_heart_overlay_scope.dart';
typedef PlayerLongPressStartCallback =
void Function(LongPressStartDetails details, double width);
/// 播放画面共用的单击/双击仲裁层。
class PlayerTapGestureRegion extends StatefulWidget {
const PlayerTapGestureRegion({
super.key,
required this.gestureKey,
required this.onSingleTap,
required this.onLongPressStart,
required this.onInteractionEnd,
this.onDoubleTapLike,
this.doubleTapEnabled = true,
this.enabled = true,
this.now,
});
final Key gestureKey;
final VoidCallback onSingleTap;
final ValueChanged<Offset>? onDoubleTapLike;
final PlayerLongPressStartCallback onLongPressStart;
final VoidCallback onInteractionEnd;
final bool doubleTapEnabled;
final bool enabled;
final DateTime Function()? now;
@override
State<PlayerTapGestureRegion> createState() => _PlayerTapGestureRegionState();
}
class _PlayerTapGestureRegionState extends State<PlayerTapGestureRegion> {
static const Duration _singleTapDelay = Duration(milliseconds: 320);
Timer? _singleTapTimer;
DateTime? _lastDownAt;
DateTime? _blockSingleTapUntil;
bool _doubleTapDown = false;
bool _likedThisPair = false;
int _downSerial = 0;
int _tapSeq = 0;
int _nextHeartBurstId = 0;
@override
void dispose() {
_tapSeq++;
_singleTapTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return IgnorePointer(
ignoring: !widget.enabled,
child: LayoutBuilder(
builder: (context, constraints) => Listener(
onPointerUp: (_) => widget.onInteractionEnd(),
onPointerCancel: (_) => widget.onInteractionEnd(),
onPointerDown: _handlePointerDown,
child: Stack(
fit: StackFit.expand,
clipBehavior: Clip.none,
children: [
GestureDetector(
key: widget.gestureKey,
behavior: HitTestBehavior.opaque,
onTapUp: _handleTapUp,
onLongPressStart: (details) =>
_handleLongPressStart(details, constraints.maxWidth),
onLongPressEnd: (_) => widget.onInteractionEnd(),
onLongPressCancel: widget.onInteractionEnd,
),
],
),
),
),
);
}
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;
}
_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)) {
_handleDoubleTapLike(details.globalPosition);
return;
}
final serial = _downSerial;
final tapSeq = ++_tapSeq;
_singleTapTimer?.cancel();
late final Timer pending;
pending = Timer(_singleTapDelay, () {
if (!identical(_singleTapTimer, pending)) return;
_singleTapTimer = null;
if (!mounted || tapSeq != _tapSeq || serial != _downSerial) return;
if (_doubleTapDown || _singleTapBlocked(_now())) return;
_lastDownAt = null;
widget.onSingleTap();
});
_singleTapTimer = pending;
}
void _handleDoubleTapLike(Offset globalPosition) {
_blockSingleTapUntil = _now().add(_singleTapDelay);
_cancelPendingSingleTap();
if (!widget.doubleTapEnabled || _likedThisPair) return;
_likedThisPair = true;
_showHeartBurst(globalPosition);
widget.onDoubleTapLike?.call(globalPosition);
}
void _showHeartBurst(Offset globalPosition) {
final overlay = Overlay.maybeOf(context, rootOverlay: true);
if (overlay == null) return;
final overlayBox = overlay.context.findRenderObject();
final origin = overlayBox is RenderBox
? overlayBox.globalToLocal(globalPosition)
: globalPosition;
final id = _nextHeartBurstId++;
final controller = PlayerHeartOverlayScope.maybeOf(context);
var removed = false;
late final OverlayEntry entry;
void removeEntry() {
if (removed) return;
removed = true;
controller?.untrack(id);
if (entry.mounted) entry.remove();
entry.dispose();
if (kDebugMode) {
debugPrint('[player] phase=heart-burst-entry-removed id=$id');
}
}
entry = OverlayEntry(
builder: (context) => Positioned.fill(
child: IgnorePointer(
child: PlayerDoubleTapHeartBurst(
key: ValueKey('heart-overlay-$id'),
burstId: id,
origin: origin,
now: widget.now,
onCompleted: removeEntry,
),
),
),
);
controller?.track(id, entry);
overlay.insert(entry);
}
void _handleLongPressStart(LongPressStartDetails details, double width) {
_tapSeq++;
_cancelPendingSingleTap();
_doubleTapDown = false;
_lastDownAt = null;
widget.onLongPressStart(details, width);
}
}
@@ -49,7 +49,8 @@ class PlayerBlockedNotice extends StatelessWidget {
bool get _needsUnlock =>
accessType == PlayTicket.coinRequired ||
accessType == PlayTicket.vipRequired;
accessType == PlayTicket.vipRequired ||
(accessType == null && episode.locked);
@override
Widget build(BuildContext context) {
@@ -5,89 +5,180 @@ import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import '../../../core/theme/app_colors.dart';
import 'player_opening_frame.dart';
const Duration _videoFadeDuration = Duration(milliseconds: 200);
const Duration _crossFadeDuration = Duration(milliseconds: 180);
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,
this.openingFrame,
this.placeholder,
this.warmFrameAvailable = false,
this.thumbnailReady = false,
this.posterReady = false,
this.fallback = PlayerOpeningFallback.black,
this.warmSlotReused = false,
this.waitForPlaybackFrame = false,
this.debugSlot = 'default',
this.debugIndex,
this.showFallbackBackground = true,
this.onVideoVisible,
});
final VideoPlayerController? controller;
final VideoPlayerController? handoff;
/// 解码出第一帧之前垫上的视频首帧,没有则为空。
final Widget? openingFrame;
/// 视频首帧未确认时唯一的占位 widget。
final Widget? placeholder;
/// 相邻集预热槽已可用时直接出视频,不挂载占位。
final bool warmFrameAvailable;
/// 当前集 t=0 雪碧图是否已命中缓存,仅用于调试判定链。
final bool thumbnailReady;
/// 当前集高清 poster 是否已下发,仅用于调试判定链。
final bool posterReady;
/// 首个视频帧确认前实际选择的唯一占位来源。
final PlayerOpeningFallback fallback;
/// 当前集是否为相邻集预热槽晋升而来。
final bool warmSlotReused;
/// 自动播放中的新集等待 position 首次前进后再移交画面。
final bool waitForPlaybackFrame;
final String debugSlot;
final int? debugIndex;
final bool showFallbackBackground;
final String videoUrl;
final bool theater;
final VoidCallback? onVideoVisible;
@override
State<PlayerVideoSurface> createState() => _PlayerVideoSurfaceState();
}
class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
String? _lastDebugState;
class _PlayerVideoSurfaceState extends State<PlayerVideoSurface>
with SingleTickerProviderStateMixin {
late final AnimationController _crossFade;
VideoPlayerController? _attachedController;
Widget? _placeholderSnapshot;
Size? _videoSize;
bool _playbackStarted = false;
bool _frameConfirmed = false;
bool _confirmationScheduled = false;
bool _transitioning = false;
bool _videoVisible = false;
bool _videoVisibleNotified = false;
String? _lastLayerState;
@override
void initState() {
super.initState();
_crossFade = AnimationController(vsync: this, duration: _crossFadeDuration)
..addStatusListener(_handleFadeStatus);
_placeholderSnapshot = widget.placeholder;
_attachController(widget.controller);
final value = widget.controller?.value;
_updatePlaybackFlags(value);
_videoSize = value != null && value.isInitialized ? value.size : null;
_logSlot('init', value);
if (_firstFrameConfirmed(value)) {
_confirmFirstFrame(initial: true);
} else {
_logLayer('placeholder', value);
}
}
@override
void didUpdateWidget(covariant PlayerVideoSurface oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) _lastDebugState = null;
if (oldWidget.controller != widget.controller) {
_logSlot('controller-change-before', oldWidget.controller?.value);
_detachController(oldWidget.controller);
_resetForControllerChange();
_attachController(widget.controller);
final value = widget.controller?.value;
_updatePlaybackFlags(value);
_videoSize = value != null && value.isInitialized ? value.size : null;
_logSlot('controller-change-after', value);
if (_firstFrameConfirmed(value)) {
_confirmFirstFrame(initial: true);
} else {
_logLayer('placeholder', value);
}
return;
}
if (!_transitioning &&
!_videoVisible &&
oldWidget.placeholder != widget.placeholder) {
_placeholderSnapshot = widget.placeholder;
}
if (oldWidget.thumbnailReady != widget.thumbnailReady ||
oldWidget.posterReady != widget.posterReady ||
oldWidget.fallback != widget.fallback ||
oldWidget.warmSlotReused != widget.warmSlotReused ||
oldWidget.warmFrameAvailable != widget.warmFrameAvailable) {
final value = widget.controller?.value;
_updatePlaybackFlags(value);
if (!_frameConfirmed && _firstFrameConfirmed(value)) {
_confirmFirstFrame();
} else {
_logLayer('placeholder', value);
}
}
}
@override
void dispose() {
_logSlot('dispose', widget.controller?.value);
_detachController(widget.controller);
_crossFade
..removeStatusListener(_handleFadeStatus)
..dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final controller = widget.controller;
if (controller == null) return _frame(null);
return ValueListenableBuilder<VideoPlayerValue>(
valueListenable: controller,
builder: (context, value, _) => _frame(value),
);
}
Widget _frame(VideoPlayerValue? value) {
final controller = widget.controller;
final handoff = _liveHandoff(controller);
final reveal = _shouldReveal(value, handoff != null);
_logStateChange(value);
final value = controller?.value;
final videoSize = _videoSize;
final showVideo = controller != null && videoSize != null;
final showPlaceholder = !_videoVisible && _placeholderSnapshot != null;
final video = showVideo
? _VideoLayer(
controller: controller,
size: videoSize,
theater: widget.theater,
)
: null;
return Stack(
fit: StackFit.expand,
children: [
const ColoredBox(
key: Key('player-fallback-background'),
color: AppColors.mediaBlack,
),
if (!reveal && widget.openingFrame != null)
KeyedSubtree(
key: const Key('player-opening-frame'),
child: widget.openingFrame!,
if (widget.showFallbackBackground)
const ColoredBox(
key: Key('player-fallback-background'),
color: AppColors.mediaBlack,
),
AnimatedOpacity(
key: const Key('player-video-opacity'),
opacity: reveal ? 1 : 0,
duration: handoff != null ? Duration.zero : _videoFadeDuration,
curve: Curves.easeOut,
child: reveal && controller != null
? _VideoLayer(
controller: controller,
value: value!,
theater: widget.theater,
)
: const SizedBox.expand(),
),
if (handoff != null)
_VideoLayer(
key: const Key('player-video-handoff'),
controller: handoff,
value: handoff.value,
theater: widget.theater,
if (showPlaceholder)
KeyedSubtree(
key: const Key('player-single-placeholder'),
child: _placeholderSnapshot!,
),
if (_videoVisible && video != null)
KeyedSubtree(key: const Key('player-video-layer'), child: video)
else if (_transitioning && video != null)
FadeTransition(
key: const Key('player-video-crossfade'),
opacity: _crossFade,
child: video,
),
if (kDebugMode && value?.hasError == true)
Center(
@@ -107,77 +198,242 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
);
}
bool _shouldReveal(VideoPlayerValue? value, bool covered) {
if (covered) return value?.isInitialized ?? false;
if (value == null || value.hasError || !value.isInitialized) return false;
return value.size.width > 0 && value.size.height > 0;
void _attachController(VideoPlayerController? controller) {
_attachedController = controller;
controller?.addListener(_handleControllerChanged);
}
/// 只画会话仍持有的旧画面,控制器一旦被换掉就不再引用。
VideoPlayerController? _liveHandoff(VideoPlayerController? controller) {
final handoff = widget.handoff;
if (handoff == null || identical(handoff, controller)) return null;
return handoff;
void _detachController(VideoPlayerController? controller) {
controller?.removeListener(_handleControllerChanged);
if (_attachedController == controller) _attachedController = null;
}
void _logStateChange(VideoPlayerValue? value) {
void _handleControllerChanged() {
final value = widget.controller?.value;
final nextSize = value != null && value.isInitialized ? value.size : null;
final sizeChanged = nextSize != _videoSize;
_updatePlaybackFlags(value);
_videoSize = nextSize;
if (!_frameConfirmed && _firstFrameConfirmed(value)) {
_scheduleFirstFrameConfirmation();
} else if (sizeChanged && mounted) {
setState(() {});
}
}
void _updatePlaybackFlags(VideoPlayerValue? value) {
_playbackStarted = _playbackStarted || value?.isPlaying == true;
}
void _scheduleFirstFrameConfirmation() {
if (_confirmationScheduled || _frameConfirmed) return;
_confirmationScheduled = true;
if (kDebugMode) {
debugPrint(
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} '
'slot=${widget.debugSlot} index=${widget.debugIndex ?? '-'} '
'phase=first-frame-scheduled',
);
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (kDebugMode) {
debugPrint(
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} '
'slot=${widget.debugSlot} index=${widget.debugIndex ?? '-'} '
'phase=first-frame-callback mounted=$mounted',
);
}
_confirmationScheduled = false;
if (!mounted || _frameConfirmed) return;
if (_firstFrameConfirmed(widget.controller?.value)) {
_confirmFirstFrame();
}
});
WidgetsBinding.instance.scheduleFrame();
}
bool _firstFrameConfirmed(VideoPlayerValue? value) {
if (value == null ||
!value.isInitialized ||
value.hasError ||
value.size.width <= 0 ||
value.size.height <= 0) {
return false;
}
if (widget.warmFrameAvailable || !widget.waitForPlaybackFrame) return true;
if (value.position > Duration.zero || value.isCompleted) return true;
return _playbackStarted && !value.isPlaying && !value.isBuffering;
}
void _confirmFirstFrame({bool initial = false}) {
if (_frameConfirmed || _videoSize == null) return;
_frameConfirmed = true;
_logSlot('firstFrameRendered', widget.controller?.value);
final canSkipPlaceholder =
widget.warmFrameAvailable || _placeholderSnapshot == null;
if (canSkipPlaceholder) {
if (initial) {
_videoVisible = true;
_placeholderSnapshot = null;
} else {
setState(() {
_videoVisible = true;
_placeholderSnapshot = null;
});
}
_logLayer('video', widget.controller?.value);
_notifyVideoVisible();
return;
}
if (initial) {
_transitioning = true;
_logLayer('fade-start', widget.controller?.value);
_crossFade.forward(from: 0);
} else {
setState(() {
_transitioning = true;
_placeholderSnapshot = widget.placeholder;
});
_logLayer('fade-start', widget.controller?.value);
_crossFade.forward(from: 0);
}
}
void _handleFadeStatus(AnimationStatus status) {
if (status != AnimationStatus.completed || !mounted) return;
setState(() {
_transitioning = false;
_videoVisible = true;
_placeholderSnapshot = null;
});
_logLayer('fade-end', widget.controller?.value);
_notifyVideoVisible();
}
void _resetForControllerChange() {
_crossFade.reset();
_placeholderSnapshot = widget.placeholder;
_videoSize = null;
_playbackStarted = false;
_frameConfirmed = false;
_confirmationScheduled = false;
_transitioning = false;
_videoVisible = false;
_videoVisibleNotified = false;
_lastLayerState = null;
}
void _notifyVideoVisible() {
if (_videoVisibleNotified) return;
_videoVisibleNotified = true;
final callback = widget.onVideoVisible;
if (callback == null) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) callback();
});
}
void _logLayer(String phase, VideoPlayerValue? value) {
if (!kDebugMode) return;
final status = _debugStatus(value);
final fallback = phase == 'video' || phase == 'fade-end'
? 'video'
: _fallbackLabel(widget.fallback);
final signature =
'$status|${value?.isInitialized ?? false}|'
'${value?.errorDescription ?? 'none'}';
if (signature == _lastDebugState) return;
_lastDebugState = signature;
final source = widget.controller?.dataSource ?? widget.videoUrl;
'slot=${widget.debugSlot} '
'index=${widget.debugIndex ?? '-'} '
'phase=$phase warm=${widget.warmFrameAvailable ? 1 : 0} '
'reusedWarm=${widget.warmSlotReused ? 1 : 0} '
'frame=${_frameConfirmed ? 1 : 0} '
'poster=${widget.posterReady ? 'ready' : 'none'} '
'thumbnails=${widget.thumbnailReady ? 'ready' : 'pending'} '
'fallback=$fallback '
'init=${value?.isInitialized == true ? 1 : 0} '
'position=${value?.position.inMilliseconds ?? 0} '
'playing=${value?.isPlaying == true ? 1 : 0} '
'buffering=${value?.isBuffering == true ? 1 : 0} '
'placeholder=${_placeholderLabel()}';
if (signature == _lastLayerState) return;
_lastLayerState = signature;
debugPrint(
'[video] init=${value?.isInitialized ?? false} '
'err=${value?.errorDescription ?? 'none'} host=${_host(source)}',
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} $signature',
);
}
String _debugStatus(VideoPlayerValue? value) {
if (value == null) return 'loading';
if (value.hasError) {
return 'error: ${value.errorDescription ?? 'unknown'}';
}
if (value.isBuffering) return 'buffering';
if (value.isInitialized) return 'initialized';
return 'loading';
void _logSlot(String phase, VideoPlayerValue? value) {
if (!kDebugMode) return;
debugPrint(
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} '
'slot=${widget.debugSlot} index=${widget.debugIndex ?? '-'} '
'phase=$phase state=${identityHashCode(this)} '
'controller=${widget.controller == null ? '-' : identityHashCode(widget.controller)} '
'init=${value?.isInitialized == true ? 1 : 0}',
);
}
String _host(String source) {
final uri = Uri.tryParse(source);
if (uri == null || uri.host.isEmpty) return 'unknown';
final port = uri.hasPort
? uri.port
: uri.scheme == 'https'
? 443
: 80;
return '${uri.host}:$port';
String _placeholderLabel() {
if (_placeholderSnapshot == null) return 'none';
return switch (widget.fallback) {
PlayerOpeningFallback.handoff => 'handoff',
PlayerOpeningFallback.poster => 'poster',
PlayerOpeningFallback.thumbnails => 'thumbnails',
PlayerOpeningFallback.black => 'none',
};
}
String _fallbackLabel(PlayerOpeningFallback fallback) {
if (_placeholderSnapshot == null) return 'black';
return switch (fallback) {
PlayerOpeningFallback.handoff => 'handoff',
PlayerOpeningFallback.poster => 'poster',
PlayerOpeningFallback.thumbnails => 'thumbnails-first-frame',
PlayerOpeningFallback.black => 'black',
};
}
}
class _VideoLayer extends StatelessWidget {
const _VideoLayer({
/// 将旧 controller 作为唯一占位,不额外叠加 handoff 层。
class ControllerFramePlaceholder extends StatelessWidget {
const ControllerFramePlaceholder({
super.key,
required this.controller,
required this.value,
required this.theater,
});
final VideoPlayerController controller;
final VideoPlayerValue value;
final bool theater;
@override
Widget build(BuildContext context) {
final size = controller.value.size;
return FittedBox(
fit: theater ? BoxFit.contain : BoxFit.cover,
child: SizedBox(
width: value.size.width,
height: value.size.height,
width: size.width,
height: size.height,
child: VideoPlayer(controller, key: ValueKey(controller)),
),
);
}
}
class _VideoLayer extends StatelessWidget {
const _VideoLayer({
required this.controller,
required this.size,
required this.theater,
});
final VideoPlayerController controller;
final Size size;
final bool theater;
@override
Widget build(BuildContext context) => FittedBox(
fit: theater ? BoxFit.contain : BoxFit.cover,
child: SizedBox(
width: size.width,
height: size.height,
child: VideoPlayer(controller, key: ValueKey(controller)),
),
);
}
@@ -9,7 +9,6 @@ import 'package:flutter/material.dart';
import '../../../core/data/services/playback_thumbnail_service.dart';
import '../../../core/data/services/sprite_thumbnail_axis.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/remote_image.dart';
const double scrubPreviewWidth = 96;
const double scrubPreviewSafeMargin = 12;
@@ -36,7 +35,6 @@ class ScrubPreviewCard extends StatefulWidget {
super.key,
required this.service,
required this.episodeId,
required this.posterUrl,
required this.position,
required this.duration,
this.spriteAxisService,
@@ -47,7 +45,6 @@ class ScrubPreviewCard extends StatefulWidget {
final SpriteThumbnailAxisSource? spriteAxisService;
final String? thumbnailsUrl;
final String episodeId;
final String posterUrl;
final Duration position;
final Duration duration;
@@ -207,11 +204,9 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
child: Stack(
fit: StackFit.expand,
children: [
RemoteImage(
widget.posterUrl,
key: const Key('scrub-preview-poster'),
fit: BoxFit.cover,
fallbackColor: AppColors.bar,
const ColoredBox(
key: Key('scrub-preview-background'),
color: AppColors.bar,
),
if (stage == ScrubPreviewStage.sprite && spriteFrame != null)
SpriteCropPreview(
@@ -256,26 +251,33 @@ class SpriteCropPreview extends StatelessWidget {
super.key,
required this.image,
required this.sourceRect,
this.fit = BoxFit.cover,
});
final ui.Image image;
final ui.Rect sourceRect;
final BoxFit fit;
@override
Widget build(BuildContext context) => CustomPaint(
painter: _SpriteCropPainter(image: image, sourceRect: sourceRect),
painter: _SpriteCropPainter(image: image, sourceRect: sourceRect, fit: fit),
);
}
class _SpriteCropPainter extends CustomPainter {
const _SpriteCropPainter({required this.image, required this.sourceRect});
const _SpriteCropPainter({
required this.image,
required this.sourceRect,
required this.fit,
});
final ui.Image image;
final ui.Rect sourceRect;
final BoxFit fit;
@override
void paint(Canvas canvas, Size size) {
final fitted = applyBoxFit(BoxFit.cover, sourceRect.size, size);
final fitted = applyBoxFit(fit, sourceRect.size, size);
final sourceOffset = Alignment.center.inscribe(
fitted.source,
Offset.zero & sourceRect.size,
@@ -302,7 +304,9 @@ class _SpriteCropPainter extends CustomPainter {
@override
bool shouldRepaint(covariant _SpriteCropPainter oldDelegate) =>
oldDelegate.image != image || oldDelegate.sourceRect != sourceRect;
oldDelegate.image != image ||
oldDelegate.sourceRect != sourceRect ||
oldDelegate.fit != fit;
}
String _format(Duration value) {
+50 -10
View File
@@ -41,8 +41,9 @@ class SeekProgressBar extends StatefulWidget {
this.thumbnailService,
this.spriteAxisService,
this.episodeId,
this.posterUrl = '',
this.thumbnailsUrl,
this.fallbackDuration = Duration.zero,
this.suppressBufferLoading = false,
});
final ValueListenable<VideoPlayerValue>? valueListenable;
@@ -57,8 +58,9 @@ class SeekProgressBar extends StatefulWidget {
final PlaybackThumbnailService? thumbnailService;
final SpriteThumbnailAxisService? spriteAxisService;
final String? episodeId;
final String posterUrl;
final String? thumbnailsUrl;
final Duration fallbackDuration;
final bool suppressBufferLoading;
@override
State<SeekProgressBar> createState() => _SeekProgressBarState();
@@ -74,6 +76,7 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
bool _pointerMoved = false;
Offset? _pointerStart;
double? _dragStartFraction;
Duration? _lastPosition;
@override
void initState() {
@@ -90,13 +93,22 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
_bufferTimer?.cancel();
_bufferTimer = null;
_buffering = false;
_lastPosition = null;
widget.thumbnailService?.cancelPending();
_attachSource();
}
if (oldWidget.suppressBufferLoading != widget.suppressBufferLoading) {
_bufferTimer?.cancel();
_bufferTimer = null;
_lastPosition = null;
_buffering = false;
_syncBufferState(notify: false);
}
if (oldWidget.locked != widget.locked) {
_bufferTimer?.cancel();
_bufferTimer = null;
_buffering = false;
_lastPosition = null;
if (widget.locked) {
widget.thumbnailService?.cancelPending();
_previewFraction.value = null;
@@ -130,14 +142,24 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
void _syncBufferState({bool notify = true}) {
final source = widget.valueListenable;
if (widget.locked || source == null) {
if (widget.locked || widget.suppressBufferLoading || source == null) {
_bufferTimer?.cancel();
_bufferTimer = null;
_lastPosition = null;
_setBuffering(false, notify: notify);
return;
}
final value = source.value;
if (!value.isInitialized) {
_bufferTimer?.cancel();
_bufferTimer = null;
_lastPosition = null;
_setBuffering(false, notify: notify);
return;
}
final previousPosition = _lastPosition;
_lastPosition = value.position;
if (previousPosition != null && value.position > previousPosition) {
_bufferTimer?.cancel();
_bufferTimer = null;
_setBuffering(false, notify: notify);
@@ -149,14 +171,24 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
_setBuffering(false, notify: notify);
return;
}
// 首次看到“已播放且有画面”的 buffering 状态时,以 position 为基线,
// 不抢先显示 loading;后续 position 停滞超过阈值才视为真实卡顿。
if (previousPosition == null &&
value.isPlaying &&
value.position > Duration.zero) {
_setBuffering(false, notify: notify);
return;
}
if (_buffering || _bufferTimer != null) return;
final bufferingPosition = value.position;
_bufferTimer = Timer(_bufferDebounce, () {
_bufferTimer = null;
final current = widget.valueListenable;
if (!mounted ||
current != source ||
!current!.value.isInitialized ||
!current.value.isBuffering) {
!current.value.isBuffering ||
current.value.position != bufferingPosition) {
return;
}
_setBuffering(true);
@@ -222,9 +254,16 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
}
Widget _buildTrack(BuildContext context, VideoPlayerValue video) {
final total = video.duration.inMilliseconds;
final duration = video.duration > Duration.zero
? video.duration
: widget.fallbackDuration;
final total = duration.inMilliseconds;
final scrubbing = _dragging;
final loading = !widget.locked && !scrubbing && _buffering;
final loading =
!widget.locked &&
!widget.suppressBufferLoading &&
!scrubbing &&
_buffering;
final enabled =
!widget.locked &&
video.isInitialized &&
@@ -236,10 +275,12 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
final fraction = _previewFraction.value ?? played;
final previewPosition = _previewFraction.value == null
? video.position
: seekPositionForFraction(fraction, video.duration);
: seekPositionForFraction(fraction, duration);
final showPreview =
scrubbing &&
widget.showTimes &&
video.isInitialized &&
total > 0 &&
widget.thumbnailService != null &&
(widget.episodeId?.isNotEmpty ?? false);
final trackHeight = scrubbing ? 6.0 : 2.0;
@@ -254,7 +295,7 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Text(
'${_format(previewPosition)} / ${_format(video.duration)}',
'${_format(previewPosition)} / ${_format(duration)}',
textAlign: TextAlign.center,
style: const TextStyle(
color: AppColors.onPrimary,
@@ -351,9 +392,8 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
spriteAxisService: widget.spriteAxisService,
thumbnailsUrl: widget.thumbnailsUrl,
episodeId: widget.episodeId!,
posterUrl: widget.posterUrl,
position: previewPosition,
duration: video.duration,
duration: duration,
),
),
],
+7 -5
View File
@@ -509,11 +509,13 @@ Widget _heat(int count, AppLocalizations l10n) {
size: 11,
),
const SizedBox(width: 4),
Text(
l10n.heatLabel(formatPlayCount(count)),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: AppColors.textTertiary, fontSize: 11),
Flexible(
child: Text(
l10n.heatLabel(formatPlayCount(count)),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(color: AppColors.textTertiary, fontSize: 11),
),
),
],
);
@@ -0,0 +1,477 @@
// 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/models/home_feed.dart';
import '../../core/data/remote/catalog_api.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/theme/app_colors.dart';
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 '../player/open_player.dart';
import 'widgets/home_hero_carousel.dart';
import 'widgets/home_recommend_content.dart';
import 'widgets/recommend_channel_nav.dart';
/// 底部第二个 tab「推荐」(礼花)。
///
/// 频道全部来自分类接口;内容区是一个横向 [PageView],左右滑动即可切换频道,
/// 顶部频道导航随之高亮,并把选中频道滚动到可见区域。
/// 第一个频道(接口的「精选」)在网格顶部额外挂一张 banners 轮播图,
/// 轮播数据来自 `GET /app/home/feed`。
class RecommendDiscoverPage extends StatefulWidget {
const RecommendDiscoverPage({
super.key,
required this.active,
required this.onSearch,
this.onOpenWallet,
});
final bool active;
final VoidCallback onSearch;
/// 顶部金色礼物盒(钱包入口)。
final VoidCallback? onOpenWallet;
@override
State<RecommendDiscoverPage> createState() => _RecommendDiscoverPageState();
}
class _RecommendDiscoverPageState extends State<RecommendDiscoverPage>
with AutomaticKeepAliveClientMixin<RecommendDiscoverPage> {
/// 当前频道 id;频道全部来自分类接口,首项即「精选」。
String? _channelId;
final Set<String> _requestedCategories = {};
final PageController _pageController = PageController();
/// `GET /app/home/feed` 返回的轮播图,只挂在第一个「精选」频道。
List<FeedBanner> _banners = const [];
bool _bannersRequested = false;
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _loadBanners());
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
/// 点击顶部频道:更新高亮并让 PageView 滑到对应页。
void _selectChannel(String id, int index) {
if (id == _channelId && _pageController.hasClients) {
// 已在该页时仍允许回到顶部对齐。
return;
}
setState(() => _channelId = id);
_ensureCategory(id);
if (_pageController.hasClients) {
unawaited(
_pageController.animateToPage(
index,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
),
);
}
}
/// 左右滑动翻页:更新高亮(不反向驱动 PageView)。
void _onPageChanged(int index, List<String> orderedIds) {
if (index < 0 || index >= orderedIds.length) return;
final id = orderedIds[index];
if (id != _channelId) setState(() => _channelId = id);
_ensureCategory(id);
}
void _ensureCategory(String id) {
if (_requestedCategories.contains(id)) return;
_requestedCategories.add(id);
final categories = context.read<CategoryController>();
if (categories.dramaPageLoader == null) return;
final slot = categories.slotOf(id);
if (slot.dramas.isNotEmpty || slot.loading) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(categories.openCategory(id));
});
}
/// 下拉刷新:重拉该分类第一页;精选频道同时刷新轮播图。
Future<void> _refreshCategory(String id, bool isFeatured) async {
final categories = context.read<CategoryController>();
final tasks = <Future<void>>[categories.openCategory(id)];
if (isFeatured) tasks.add(_loadBanners(force: true));
await Future.wait(tasks);
}
/// 轮播图只依赖 home/feed 的 banners;接口缺失(如测试注入)时静默跳过,
/// 不影响下方分类网格。
Future<void> _loadBanners({bool force = false}) async {
if (_bannersRequested && !force) return;
_bannersRequested = true;
CatalogApi? api;
try {
api = context.read<CatalogApi>();
} on ProviderNotFoundException {
api = null;
}
if (api == null) return;
try {
final feed = await api.homeFeed();
if (mounted && feed.banners.isNotEmpty) {
setState(() => _banners = feed.banners);
}
} catch (_) {
// 轮播拉取失败时保留纯网格。
}
}
Future<void> _openDrama(Drama drama) =>
playDramaFromCatalog(context, drama);
@override
Widget build(BuildContext context) {
super.build(context);
final categories = context.watch<CategoryController>();
final mediaTop = MediaQuery.of(context).padding.top;
final categoryList = categories.categories;
final orderedIds = categoryList.map((c) => c.id).toList();
// 频道来自接口分类;默认选中第一个分类(即「精选」)。
_channelId ??= categoryList.isEmpty ? null : categoryList.first.id;
final selectedIndex = _channelId == null
? 0
: orderedIds.indexOf(_channelId!).clamp(0, orderedIds.length - 1);
return ColoredBox(
key: const Key('recommend-page'),
color: AppColors.appBackground,
child: Stack(
children: [
Positioned.fill(
child: categoryList.isEmpty
? const Center(
child: CircularProgressIndicator(
color: AppColors.brandRed,
),
)
: PageView.builder(
key: const Key('recommend-channel-pager'),
controller: _pageController,
itemCount: categoryList.length,
onPageChanged: (i) => _onPageChanged(i, orderedIds),
itemBuilder: (context, index) {
final category = categoryList[index];
return _ChannelFeed(
key: PageStorageKey<String>(
'recommend-channel-${category.id}',
),
categoryId: category.id,
isFeatured: index == 0,
banners: _banners,
carouselActive: widget.active && index == selectedIndex,
mediaTop: mediaTop,
onRequest: _ensureCategory,
onRefresh: () => _refreshCategory(category.id, index == 0),
onOpenDrama: _openDrama,
);
},
),
),
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: SizedBox(
height: mediaTop + RecommendChannelNav.height,
child: const DecoratedBox(
key: Key('recommend-top-gradient'),
decoration: 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: RecommendChannelNav(
categories: categoryList,
selectedId: _channelId,
onSelected: (id) {
final index = orderedIds.indexOf(id);
if (index >= 0) _selectChannel(id, index);
},
onSearch: widget.onSearch,
onGift: widget.onOpenWallet,
),
),
),
],
),
);
}
}
/// 单个分类频道的内容:可选顶部轮播 + 该分类短剧三列网格。
class _ChannelFeed extends StatefulWidget {
const _ChannelFeed({
super.key,
required this.categoryId,
required this.isFeatured,
required this.banners,
required this.carouselActive,
required this.mediaTop,
required this.onRequest,
required this.onRefresh,
required this.onOpenDrama,
});
final String categoryId;
final bool isFeatured;
final List<FeedBanner> banners;
final bool carouselActive;
final double mediaTop;
final ValueChanged<String> onRequest;
final Future<void> Function() onRefresh;
final ValueChanged<Drama> onOpenDrama;
@override
State<_ChannelFeed> createState() => _ChannelFeedState();
}
class _ChannelFeedState extends State<_ChannelFeed>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
widget.onRequest(widget.categoryId);
}
Drama? _dramaForBanner(FeedBanner banner, List<Drama> pool) {
final id = banner.dramaId;
if (id == null) return null;
for (final drama in pool) {
if (drama.id == id) return drama;
}
return null;
}
@override
Widget build(BuildContext context) {
super.build(context);
final categories = context.watch<CategoryController>();
final slot = categories.slotOf(widget.categoryId);
final dramas = slot.dramas;
final showCarousel = widget.isFeatured && widget.banners.isNotEmpty;
final bottomInset = MediaQuery.of(context).padding.bottom;
// 精选频道:按接口下发的标签(tag)把「上新」筛出来横滑,其余短剧一行两个。
List<Drama> newArrivals = const [];
List<Drama> rest = dramas;
if (widget.isFeatured && dramas.isNotEmpty) {
final lang = Localizations.localeOf(context).languageCode;
final badge = AppLocalizations.of(context)!.newArrivalBadge;
newArrivals = dramas
.where((drama) => _isNewArrivalTag(drama, lang, badge))
.toList(growable: false);
if (newArrivals.isNotEmpty) {
final newIds = newArrivals.map((drama) => drama.id).toSet();
rest = dramas
.where((drama) => !newIds.contains(drama.id))
.toList(growable: false);
}
}
final sliverList = <Widget>[];
if (showCarousel) {
sliverList.add(
SliverToBoxAdapter(
child: HomeHeroCarousel(
banners: widget.banners,
active: widget.carouselActive,
dramaFor: (banner) => _dramaForBanner(banner, dramas),
onWatch: widget.onOpenDrama,
),
),
);
}
if (dramas.isEmpty) {
sliverList.add(
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: EdgeInsets.only(
top: showCarousel ? 0 : widget.mediaTop + RecommendChannelNav.height,
),
child: Center(child: _placeholder(slot.loading)),
),
),
);
} else if (widget.isFeatured) {
// 无轮播图时内容需避开顶部悬浮导航。
final contentTop =
showCarousel ? 24.0 : widget.mediaTop + RecommendChannelNav.height + 16;
if (newArrivals.isNotEmpty) {
sliverList.add(
SliverToBoxAdapter(child: SizedBox(height: contentTop)),
);
sliverList.add(
SliverToBoxAdapter(
child: HomeNewArrivalRow(
dramas: newArrivals,
onOpen: widget.onOpenDrama,
),
),
);
sliverList.add(
const SliverToBoxAdapter(child: SizedBox(height: 28)),
);
}
sliverList.add(
_gridSliver(
rest,
topPadding: newArrivals.isNotEmpty ? 0 : contentTop,
crossAxisCount: 2,
),
);
} else {
sliverList.add(
_gridSliver(
dramas,
topPadding: showCarousel ? 20 : widget.mediaTop + RecommendChannelNav.height + 16,
crossAxisCount: 3,
),
);
}
sliverList.add(
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.only(bottom: bottomInset),
child: PagedListFooter(
key: const Key('recommend-category-footer'),
loading: slot.loadingMore,
hasMore: slot.hasMore,
hasItems: dramas.isNotEmpty,
errorMessage: null,
onRetry: () => categories.loadMore(widget.categoryId),
),
),
),
);
return NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (notification.depth != 0) return false;
if (notification.metrics.extentAfter > 300) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification &&
notification is! OverscrollNotification) {
return false;
}
unawaited(categories.loadMore(widget.categoryId));
return false;
},
child: AppPullToRefresh(
onRefresh: widget.onRefresh,
child: CustomScrollView(
key: PageStorageKey<String>('recommend-feed-${widget.categoryId}'),
physics: AppPullToRefresh.physics,
slivers: sliverList,
),
),
);
}
Widget _placeholder(bool loading) {
if (loading) {
return const CircularProgressIndicator(color: AppColors.brandRed);
}
final l10n = AppLocalizations.of(context)!;
return EmptyState(
key: const Key('recommend-category-empty'),
icon: Icons.movie_outlined,
title: l10n.noStories,
);
}
Widget _gridSliver(
List<Drama> dramas, {
required double topPadding,
required int crossAxisCount,
}) {
const pageSide = 14.0;
const cardGap = 9.0;
const rowGap = 16.0;
const cardBodyExtent = 44.0; // 封面下间距 + 剧名行 + 集数行
// 两列时卡更大,卡间距略放宽。
final spacing = crossAxisCount == 2 ? 12.0 : cardGap;
return SliverPadding(
padding: EdgeInsets.fromLTRB(pageSide, topPadding, pageSide, 0),
sliver: SliverLayoutBuilder(
builder: (context, constraints) {
final itemWidth =
(constraints.crossAxisExtent - spacing * (crossAxisCount - 1)) /
crossAxisCount;
final itemExtent = itemWidth * 157 / 110 + cardBodyExtent;
return SliverGrid(
key: Key('recommend-category-grid-${widget.categoryId}'),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
crossAxisSpacing: spacing,
mainAxisSpacing: rowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
final drama = dramas[index];
return HomePosterCard(
key: Key('recommend-category-card-${drama.id}'),
drama: drama,
onTap: () => widget.onOpenDrama(drama),
);
},
childCount: dramas.length,
),
);
},
),
);
}
}
/// 判定接口下发的短剧标签是否为「上新」。
///
/// 完全以后端返回的 `tag` / `tagLocales`(经 [Drama.localizedTag] 本地化)
/// 为准;兼容「上新 / NEW / BARU」三种文案,并兼容「本周上新」这类带前后缀的写法。
bool _isNewArrivalTag(Drama drama, String lang, String localizedBadge) {
final tag = drama.localizedTag(lang).trim();
if (tag.isEmpty) return false;
if (tag == localizedBadge) return true;
final lower = tag.toLowerCase();
return tag.contains('上新') || lower == 'new' || lower == 'baru';
}
+167 -33
View File
@@ -14,6 +14,7 @@ import '../../core/data/services/playlist_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../home/home_feed_channel.dart';
import '../player/open_player.dart';
import '../player/player_view.dart';
import 'recommend_types.dart';
@@ -29,6 +30,7 @@ class RecommendPage extends StatefulWidget {
this.catalogApi,
required this.active,
required this.onSearch,
this.onOpenWallet,
this.videoOnly = false,
this.onImmersiveChanged,
});
@@ -38,6 +40,9 @@ class RecommendPage extends StatefulWidget {
final bool active;
final VoidCallback onSearch;
/// 顶部金色礼物盒(钱包入口)。
final VoidCallback? onOpenWallet;
/// 画中画时只留视频,不画顶栏。
final bool videoOnly;
final ValueChanged<bool>? onImmersiveChanged;
@@ -46,30 +51,102 @@ class RecommendPage extends StatefulWidget {
State<RecommendPage> createState() => _RecommendPageState();
}
class _RecommendPageState extends State<RecommendPage> {
class _RecommendPageState extends State<RecommendPage>
with AutomaticKeepAliveClientMixin<RecommendPage> {
static const Duration _recommendRetryDelay = Duration(milliseconds: 1500);
static const int _maxRecommendRetries = 3;
RecommendInnerTab _tab = RecommendInnerTab.feed;
final PageController _pageController = PageController();
int _scrubCancelRequest = 0;
bool _recommendDataRefreshScheduled = false;
bool _recommendRefreshInFlight = false;
int _recommendRetryAttempts = 0;
Timer? _recommendRetryTimer;
HomeFeedChannel? _observedFeedChannel;
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
_observedFeedChannel = widget.feedController.channel;
widget.feedController.addListener(_handleFeedControllerChanged);
if (widget.active) _scheduleRecommendData();
}
@override
void didUpdateWidget(RecommendPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.active && !oldWidget.active) _scheduleRecommendData();
if (oldWidget.feedController != widget.feedController) {
oldWidget.feedController.removeListener(_handleFeedControllerChanged);
_cancelRecommendRetries();
_observedFeedChannel = widget.feedController.channel;
widget.feedController.addListener(_handleFeedControllerChanged);
}
if (oldWidget.active && !widget.active) {
_cancelRecommendRetries();
}
if (_requiresRecommendDataRefresh(oldWidget)) {
_scheduleRecommendData();
}
}
bool _requiresRecommendDataRefresh(RecommendPage oldWidget) {
if (!widget.active) return false;
return !oldWidget.active ||
oldWidget.feedController != widget.feedController ||
oldWidget.catalogApi != widget.catalogApi;
}
void _handleFeedControllerChanged() {
final channel = widget.feedController.channel;
if (channel != _observedFeedChannel) {
_observedFeedChannel = channel;
_cancelRecommendRetries();
if (widget.active) _scheduleRecommendData();
return;
}
_handleRecommendFeedState();
}
void _handleRecommendFeedState() {
if (!mounted || !widget.active) return;
final feed = widget.feedController;
if (feed.dramas.isNotEmpty) {
_cancelRecommendRetries();
return;
}
if (feed.loaded &&
feed.lastError == null &&
!feed.isLoading &&
!_recommendRefreshInFlight) {
_cancelRecommendRetries();
return;
}
if (feed.loaded && feed.lastError != null && !_recommendRefreshInFlight) {
_scheduleRecommendRetry();
}
}
void _scheduleRecommendData() {
final feed = widget.feedController;
if (!feed.loaded && !feed.loadingFirstPage) {
unawaited(feed.refreshCurrent());
}
if (_recommendDataRefreshScheduled) return;
_recommendDataRefreshScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_recommendDataRefreshScheduled = false;
if (!mounted || !widget.active) return;
final feed = widget.feedController;
if (feed.dramas.isEmpty || feed.lastError != null) {
_recommendRetryAttempts = 0;
if (!feed.isLoading && !_recommendRefreshInFlight) {
if (feed.loaded) {
_scheduleRecommendRetry();
} else {
unawaited(_refreshRecommendData());
}
}
}
final playlists = _readPlaylists();
if (playlists != null && !playlists.loaded && !playlists.loading) {
unawaited(playlists.load());
@@ -77,14 +154,58 @@ class _RecommendPageState extends State<RecommendPage> {
});
}
void _scheduleRecommendRetry() {
if (!mounted ||
!widget.active ||
_recommendRefreshInFlight ||
_recommendRetryTimer != null ||
_recommendRetryAttempts >= _maxRecommendRetries) {
return;
}
setState(() {
_recommendRetryTimer = Timer(_recommendRetryDelay, () {
_recommendRetryTimer = null;
if (!mounted || !widget.active) return;
_recommendRetryAttempts += 1;
unawaited(_refreshRecommendData());
});
});
}
Future<void> _refreshRecommendData() async {
if (!mounted || !widget.active || _recommendRefreshInFlight) return;
setState(() => _recommendRefreshInFlight = true);
final succeeded = await widget.feedController.refreshCurrent();
if (!mounted) return;
_recommendRefreshInFlight = false;
if (!widget.active) return;
final feed = widget.feedController;
if (succeeded || (feed.loaded && feed.lastError == null)) {
_cancelRecommendRetries();
setState(() {});
return;
}
setState(() {});
_scheduleRecommendRetry();
}
void _cancelRecommendRetries() {
_recommendRetryTimer?.cancel();
_recommendRetryTimer = null;
_recommendRetryAttempts = 0;
}
@override
void dispose() {
widget.feedController.removeListener(_handleFeedControllerChanged);
_cancelRecommendRetries();
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
final categories = context.read<CategoryController>();
return ColoredBox(
key: const Key('recommend-page'),
@@ -155,6 +276,7 @@ class _RecommendPageState extends State<RecommendPage> {
onVideo: _tab == RecommendInnerTab.feed,
onSelected: _selectTab,
onSearch: _handleSearch,
onGift: widget.onOpenWallet,
),
),
),
@@ -164,39 +286,51 @@ class _RecommendPageState extends State<RecommendPage> {
}
Widget _recommendFeed(BuildContext context) {
final feed = widget.feedController;
final dramas = widget.feedController.dramas;
if (dramas.isEmpty) {
final l10n = AppLocalizations.of(context)!;
if (widget.feedController.loadingFirstPage) {
return const _RecommendFeedSkeleton();
}
if (dramas.isNotEmpty) {
return PlayerPage(
key: const Key('recommend-feed-player'),
homeMode: true,
embedded: true,
active: widget.active && _tab == RecommendInnerTab.feed,
showHomeFeedHeader: false,
drama: dramas.first,
initialIndex: 0,
feedDramas: dramas,
feedChannel: widget.feedController.channel,
onOpenFullPlayer: (drama, episode) =>
_openDrama(drama, episodeId: episode.id),
onRefreshFeed: widget.feedController.refreshCurrent,
onLoadMore: widget.feedController.loadMore,
onImmersiveChanged: widget.onImmersiveChanged,
scrubCancelRequest: _scrubCancelRequest,
);
}
if (!feed.loaded ||
feed.isLoading ||
_recommendRefreshInFlight ||
_recommendRetryTimer != null) {
return const _RecommendFeedSkeleton();
}
final l10n = AppLocalizations.of(context)!;
if (feed.lastError != null) {
return ColoredBox(
color: AppColors.mediaBlack,
child: EmptyState(
key: const Key('recommend-feed-empty'),
icon: Icons.movie_outlined,
title: l10n.noStories,
actionLabel: l10n.retry,
onAction: () => unawaited(widget.feedController.refreshCurrent()),
icon: Icons.wifi_off_rounded,
title: l10n.networkError,
),
);
}
return PlayerPage(
key: const Key('recommend-feed-player'),
homeMode: true,
embedded: true,
active: widget.active && _tab == RecommendInnerTab.feed,
showHomeFeedHeader: false,
drama: dramas.first,
initialIndex: 0,
feedDramas: dramas,
feedChannel: widget.feedController.channel,
onOpenFullPlayer: (drama, episode) =>
_openDrama(drama, episodeId: episode.id),
onRefreshFeed: widget.feedController.refreshCurrent,
onLoadMore: widget.feedController.loadMore,
onImmersiveChanged: widget.onImmersiveChanged,
scrubCancelRequest: _scrubCancelRequest,
return ColoredBox(
color: AppColors.mediaBlack,
child: EmptyState(
key: const Key('recommend-feed-empty'),
icon: Icons.movie_outlined,
title: l10n.noStories,
),
);
}
@@ -391,7 +525,7 @@ class _RecommendFeedSkeleton extends StatelessWidget {
height: 176,
child: DecoratedBox(
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
color: AppColors.skeletonMedia,
borderRadius: BorderRadius.all(Radius.circular(12)),
),
),
@@ -430,7 +564,7 @@ class _SkeletonLine extends StatelessWidget {
width: width,
height: height,
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
color: AppColors.skeletonMedia,
borderRadius: BorderRadius.circular(6),
),
);
@@ -0,0 +1,396 @@
// 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/models/home_feed.dart';
import '../../../core/data/services/favorite_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
/// 推荐页顶部静态头图轮播:封面 + 居中剧名/简介 + 立即观看/收藏 + 轮播点。
class HomeHeroCarousel extends StatefulWidget {
const HomeHeroCarousel({
super.key,
required this.banners,
required this.dramaFor,
required this.onWatch,
this.active = true,
});
final List<FeedBanner> banners;
/// 按 banner 关联到的剧目;为空时只展示头图。
final Drama? Function(FeedBanner banner) dramaFor;
/// 点击「立即观看」或直接点按头图。
final ValueChanged<Drama> onWatch;
final bool active;
/// 固定轮播高度;后台按该比例(屏宽 : height)出图即可铺满不裁切。
static const double height = 420;
@override
State<HomeHeroCarousel> createState() => _HomeHeroCarouselState();
}
class _HomeHeroCarouselState extends State<HomeHeroCarousel> {
static const Duration _autoInterval = Duration(milliseconds: 4500);
static const Duration _pageDuration = Duration(milliseconds: 480);
static const double _dotSize = 4;
static const double _dotGap = 9;
static const double _ctaHeight = 38;
final PageController _controller = PageController();
Timer? _timer;
int _index = 0;
bool _pressed = false;
bool _tickerEnabled = true;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _syncTimer());
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final enabled = TickerMode.valuesOf(context).enabled;
if (enabled != _tickerEnabled) {
_tickerEnabled = enabled;
_syncTimer();
}
}
@override
void didUpdateWidget(covariant HomeHeroCarousel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.banners.length != widget.banners.length) {
if (_index >= widget.banners.length) _index = 0;
_syncTimer();
}
if (oldWidget.banners.length != widget.banners.length ||
oldWidget.active != widget.active) {
_syncTimer();
}
}
@override
void dispose() {
_timer?.cancel();
_controller.dispose();
super.dispose();
}
void _syncTimer() {
_timer?.cancel();
_timer = null;
final canAdvance = mounted &&
widget.active &&
_tickerEnabled &&
!_pressed &&
widget.banners.length > 1;
if (!canAdvance) return;
_timer = Timer.periodic(_autoInterval, (_) => _advance());
}
void _advance() {
if (!_controller.hasClients || widget.banners.length < 2) return;
final next = (_index + 1) % widget.banners.length;
_controller.animateToPage(
next,
duration: _pageDuration,
curve: Curves.easeOutCubic,
);
}
@override
Widget build(BuildContext context) {
if (widget.banners.isEmpty) return const SizedBox.shrink();
return SizedBox(
key: const Key('home-hero-carousel'),
height: HomeHeroCarousel.height,
child: Listener(
onPointerDown: (_) {
_pressed = true;
_timer?.cancel();
},
onPointerUp: (_) {
_pressed = false;
_syncTimer();
},
onPointerCancel: (_) {
_pressed = false;
_syncTimer();
},
child: Stack(
fit: StackFit.expand,
children: [
PageView.builder(
controller: _controller,
itemCount: widget.banners.length,
onPageChanged: (value) => setState(() => _index = value),
itemBuilder: (context, index) => _bannerPage(context, index),
),
Positioned(left: 0, right: 0, bottom: 14, child: _dots(context)),
],
),
),
);
}
Widget _bannerPage(BuildContext context, int index) {
final banner = widget.banners[index];
final drama = widget.dramaFor(banner);
return Stack(
fit: StackFit.expand,
children: [
RemoteImage(
banner.imageUrl,
fit: BoxFit.cover,
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0x99000000),
Color(0x00000000),
Color(0x66000000),
Color(0xB3000000),
],
stops: [0, 0.22, 0.62, 1],
),
),
),
if (drama != null)
Align(
alignment: const Alignment(0, 0.6),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 28),
child: _HeroCopy(
key: Key('home-hero-copy-$index'),
drama: drama,
ctaHeight: _ctaHeight,
onWatch: () => widget.onWatch(drama),
),
),
),
if (drama != null)
Positioned.fill(
child: Material(
color: AppColors.transparent,
child: InkWell(
key: Key('home-hero-$index'),
highlightColor: AppColors.transparent,
onTap: () => widget.onWatch(drama),
),
),
),
],
);
}
Widget _dots(BuildContext context) {
if (widget.banners.length < 2) return const SizedBox.shrink();
return ExcludeSemantics(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (var index = 0; index < widget.banners.length; index++)
Container(
key: Key('home-hero-dot-$index'),
width: _dotSize,
height: _dotSize,
margin: const EdgeInsets.symmetric(horizontal: _dotGap / 2),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: index == _index
? AppColors.brandRed
: AppColors.textPrimary.withValues(alpha: 0.4),
),
),
],
),
);
}
}
/// Hero 中部居中文案与按钮组。
class _HeroCopy extends StatelessWidget {
const _HeroCopy({
super.key,
required this.drama,
required this.ctaHeight,
required this.onWatch,
});
final Drama drama;
final double ctaHeight;
final VoidCallback onWatch;
static const Color _titleCream = Color(0xFFE9D3B8);
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final lang = Localizations.localeOf(context).languageCode;
final types = drama.localizedTypeLabels(lang);
final meta = [
if (types.isNotEmpty) types.first,
l10n.totalEpisodesShort(drama.episodeCount),
].join(' · ');
return Column(
key: const Key('home-hero-copy'),
mainAxisSize: MainAxisSize.min,
children: [
Text(
drama.localizedTitle(lang),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: const TextStyle(
color: _titleCream,
fontSize: 28,
fontWeight: FontWeight.w600,
height: 1.15,
shadows: [Shadow(color: Color(0x80000000), blurRadius: 12)],
),
),
const SizedBox(height: 8),
Text(
meta,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: AppColors.textPrimary.withValues(alpha: 0.92),
fontSize: 14,
fontWeight: FontWeight.w400,
),
),
const SizedBox(height: 10),
Text(
drama.localizedSynopsis(lang),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(
color: AppColors.textPrimary.withValues(alpha: 0.95),
fontSize: 15,
fontWeight: FontWeight.w400,
shadows: const [
Shadow(color: Color(0x80000000), blurRadius: 8),
],
),
),
const SizedBox(height: 20),
Row(
mainAxisSize: MainAxisSize.min,
children: [
_WatchButton(height: ctaHeight, label: l10n.watchNowAction, onTap: onWatch),
const SizedBox(width: 12),
_FavoriteCircle(size: ctaHeight, drama: drama),
],
),
],
);
}
}
class _WatchButton extends StatelessWidget {
const _WatchButton({
required this.height,
required this.label,
required this.onTap,
});
final double height;
final String label;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: AppColors.brandRed,
borderRadius: BorderRadius.circular(height / 2),
child: InkWell(
key: const Key('home-hero-watch'),
borderRadius: BorderRadius.circular(height / 2),
onTap: onTap,
child: SizedBox(
height: height,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.play_arrow_rounded,
size: 20,
color: AppColors.textPrimary,
),
const SizedBox(width: 2),
Text(
label,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
),
);
}
}
class _FavoriteCircle extends StatelessWidget {
const _FavoriteCircle({required this.size, required this.drama});
final double size;
final Drama drama;
@override
Widget build(BuildContext context) {
final favorites = context.watch<FavoriteController>();
final saved = favorites.isSaved(drama.id);
return Material(
color: saved ? AppColors.brandRed : AppColors.transparent,
shape: CircleBorder(
side: BorderSide(
color: saved
? AppColors.brandRed
: AppColors.textPrimary.withValues(alpha: 0.85),
width: 1.5,
),
),
child: InkWell(
key: const Key('home-hero-favorite'),
customBorder: const CircleBorder(),
onTap: () => unawaited(favorites.toggle(drama.id, card: drama)),
child: SizedBox(
width: size,
height: size,
child: Icon(
saved ? Icons.bookmark_rounded : Icons.bookmark_border_rounded,
size: 20,
color: AppColors.textPrimary,
),
),
),
);
}
}
@@ -0,0 +1,252 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
/// 设计稿(首页 1)推荐页内容区规格:
/// 海报卡 110×157、页边距 14、卡距 9、圆角 12。
const double _pageSide = 14;
const double _cardWidth = 110;
const double _cardCoverHeight = 157;
const double _cardGap = 9;
const double _cardRadius = 12;
/// 上新横滑卡板块。无板块标题,卡片左上角带「上新」角标。
/// 内层横向 ListView 会自行识别横向手势,不与外层纵向滚动冲突。
class HomeNewArrivalRow extends StatelessWidget {
const HomeNewArrivalRow({
super.key,
required this.dramas,
required this.onOpen,
});
final List<Drama> dramas;
final ValueChanged<Drama> onOpen;
@override
Widget build(BuildContext context) {
if (dramas.isEmpty) return const SizedBox.shrink();
return SizedBox(
key: const Key('home-new-arrival-row'),
height:
_cardCoverHeight + 8 + 20 + 2 + 16, // 封面 + 剧名行 + 集数行 + 余量
child: ListView.separated(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: _pageSide),
itemCount: dramas.length,
separatorBuilder: (_, _) => const SizedBox(width: _cardGap),
itemBuilder: (context, index) => SizedBox(
width: _cardWidth,
child: HomePosterCard(
key: Key('home-new-arrival-${dramas[index].id}'),
drama: dramas[index],
badge: AppLocalizations.of(context)!.newArrivalBadge,
onTap: () => onOpen(dramas[index]),
),
),
),
);
}
}
/// 110×157 海报 + 卡下剧名/集数。
///
/// 封面左上角标签优先用接口返回的短剧标签(`drama.tag` + `drama.tagColor`);
/// 接口没有标签时,若传了 [badge](如「上新」)则退回显示该角标。
class HomePosterCard extends StatelessWidget {
const HomePosterCard({
super.key,
required this.drama,
required this.onTap,
this.badge,
});
final Drama drama;
final VoidCallback onTap;
final String? badge;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final lang = Localizations.localeOf(context).languageCode;
final tag = drama.localizedTag(lang);
final tagLabel = tag.isNotEmpty ? tag : (badge ?? '');
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(_cardRadius),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(_cardRadius),
child: AspectRatio(
aspectRatio: _cardWidth / _cardCoverHeight,
child: Stack(
fit: StackFit.expand,
children: [
RemoteImage(
drama.posterUrl,
fit: BoxFit.cover,
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
if (tagLabel.isNotEmpty)
Positioned(
left: 8,
top: 8,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 3,
),
decoration: BoxDecoration(
color: tag.isNotEmpty
? drama.tagRibbonColor(AppColors.brandRed)
: AppColors.brandRed,
borderRadius: BorderRadius.circular(6),
),
child: Text(
tagLabel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 11,
fontWeight: FontWeight.w600,
height: 1.1,
),
),
),
),
],
),
),
),
const SizedBox(height: 8),
Text(
drama.localizedTitle(lang),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 14,
fontWeight: FontWeight.w500,
height: 1.2,
),
),
const SizedBox(height: 2),
Text(
l10n.totalEpisodesShort(drama.episodeCount),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textTertiary,
fontSize: 12,
height: 1.2,
),
),
],
),
);
}
}
/// 编辑精选横幅:满宽背景图 + 左上小标签、大标题、副标题。
class HomeEditorPickBanner extends StatelessWidget {
const HomeEditorPickBanner({
super.key,
required this.drama,
required this.onOpen,
});
final Drama drama;
final ValueChanged<Drama> onOpen;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final lang = Localizations.localeOf(context).languageCode;
return Padding(
key: const Key('home-editor-pick'),
padding: const EdgeInsets.symmetric(horizontal: _pageSide),
child: SizedBox(
height: 72,
child: ClipRRect(
borderRadius: BorderRadius.circular(_cardRadius),
child: Stack(
fit: StackFit.expand,
children: [
RemoteImage(
drama.posterUrl,
fit: BoxFit.cover,
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Color(0xE6000000), Color(0x4D000000), Color(0x1A000000)],
),
),
),
Positioned.fill(
child: Material(
color: AppColors.transparent,
child: InkWell(onTap: () => onOpen(drama)),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.editorPick,
maxLines: 1,
style: TextStyle(
color: AppColors.textPrimary.withValues(alpha: 0.85),
fontSize: 11,
fontWeight: FontWeight.w500,
letterSpacing: 2,
),
),
const SizedBox(height: 4),
Text(
drama.localizedTitle(lang),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: 18,
fontWeight: FontWeight.w600,
height: 1.15,
),
),
const SizedBox(height: 2),
Text(
drama.localizedSynopsis(lang),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: AppColors.textPrimary.withValues(alpha: 0.8),
fontSize: 12,
),
),
],
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,222 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import '../../../core/data/models/content_category.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
const double _navHeight = 56;
const double _tabGap = 20;
const double _tabFont = 17;
const double _searchHitSize = 40;
const double _searchIconSize = 26;
const double _giftIconSize = 30;
const double _underlineWidth = 26;
const double _underlineHeight = 3;
/// 推荐页(礼花 tab)顶部频道导航:频道全部来自分类接口,右侧搜索/礼物。
class RecommendChannelNav extends StatefulWidget {
const RecommendChannelNav({
super.key,
required this.categories,
required this.selectedId,
required this.onSelected,
required this.onSearch,
this.onGift,
});
static const double height = _navHeight;
/// 接口返回的内容分类(首项即「精选」)。
final List<ContentCategory> categories;
final String? selectedId;
final ValueChanged<String> onSelected;
final VoidCallback onSearch;
/// 右上角金色礼物盒(钱包入口);为空时不显示。
final VoidCallback? onGift;
@override
State<RecommendChannelNav> createState() => _RecommendChannelNavState();
}
class _RecommendChannelNavState extends State<RecommendChannelNav> {
static const double _revealLeftInset = 20;
final ScrollController _scrollController = ScrollController();
final GlobalKey _scrollViewKey = GlobalKey();
final Map<String, GlobalKey> _tabKeys = {};
GlobalKey _keyFor(String id) =>
_tabKeys.putIfAbsent(id, () => GlobalKey());
@override
void didUpdateWidget(covariant RecommendChannelNav oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.selectedId != null &&
(widget.selectedId != oldWidget.selectedId ||
widget.categories.length != oldWidget.categories.length)) {
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
}
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
/// 把选中频道平滑滚动到可视区域:对齐到滚动区左缘 20pt。
void _revealSelected() {
final id = widget.selectedId;
if (id == null || !_scrollController.hasClients) return;
final tabCtx = _tabKeys[id]?.currentContext;
final tabBox = tabCtx?.findRenderObject() as RenderBox?;
final scrollBox =
_scrollViewKey.currentContext?.findRenderObject() as RenderBox?;
if (tabBox == null || scrollBox == null) return;
final viewportLeft = scrollBox.localToGlobal(Offset.zero).dx;
final tabLeft = tabBox.localToGlobal(Offset.zero).dx;
final relative = tabLeft - viewportLeft;
final position = _scrollController.position;
final target =
(position.pixels + relative - _revealLeftInset)
.clamp(0.0, position.maxScrollExtent);
if ((target - position.pixels).abs() < 0.5) return;
_scrollController.animateTo(
target,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final lang = Localizations.localeOf(context).languageCode;
final categories = widget.categories;
final tabs = <(String, String, String)>[
for (final category in categories)
(category.id, category.localizedName(lang), category.id),
];
return SizedBox(
key: const Key('recommend-channel-nav'),
height: RecommendChannelNav.height,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: SingleChildScrollView(
key: _scrollViewKey,
controller: _scrollController,
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.only(left: 20, right: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (var index = 0; index < tabs.length; index++) ...[
if (index > 0) const SizedBox(width: _tabGap),
KeyedSubtree(
key: _keyFor(tabs[index].$3),
child: _tab(
key: Key('recommend-tab-${tabs[index].$3}'),
code: tabs[index].$3,
label: tabs[index].$2,
selected: widget.selectedId == tabs[index].$1,
onTap: () => widget.onSelected(tabs[index].$1),
),
),
],
],
),
),
),
SizedBox.square(
dimension: _searchHitSize,
child: IconButton(
key: const Key('recommend-search'),
tooltip: l10n.search,
onPressed: widget.onSearch,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _searchHitSize,
height: _searchHitSize,
),
iconSize: _searchIconSize,
color: AppColors.textPrimary,
icon: const Icon(Icons.search_rounded),
),
),
if (widget.onGift != null)
SizedBox.square(
dimension: _searchHitSize,
child: IconButton(
key: const Key('recommend-gift'),
tooltip: l10n.wallet,
onPressed: widget.onGift,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _searchHitSize,
height: _searchHitSize,
),
iconSize: _giftIconSize,
icon: Image.asset(
'assets/icon/gift.png',
width: _giftIconSize,
height: _giftIconSize,
fit: BoxFit.contain,
),
),
),
const SizedBox(width: 8),
],
),
);
}
Widget _tab({
required Key key,
required String code,
required String label,
required bool selected,
required VoidCallback onTap,
}) {
return GestureDetector(
key: key,
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 补偿文字下方的 4pt 间距 + 3pt 下划线,让文字视觉中心与右侧图标对齐。
const SizedBox(height: 4 + _underlineHeight),
Text(
label,
maxLines: 1,
style: TextStyle(
color: AppColors.textPrimary,
fontSize: _tabFont,
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
letterSpacing: 0,
shadows: const [
Shadow(color: AppColors.mediaBlack, blurRadius: 6),
],
),
),
const SizedBox(height: 4),
Container(
key: Key('recommend-tab-$code-underline'),
width: _underlineWidth,
height: _underlineHeight,
decoration: BoxDecoration(
color: selected ? AppColors.brandRed : AppColors.transparent,
borderRadius: BorderRadius.circular(_underlineHeight / 2),
),
),
],
),
);
}
}
@@ -3,16 +3,17 @@
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../l10n/app_localizations.dart';
import '../recommend_types.dart';
const double _navHeight = 56;
const double _tabGap = 22;
const double _tabGap = 20;
const double _tabFont = 17;
const double _searchHitSize = 40;
const double _searchIconSize = 26;
const double _minNavWidth = 280;
const double _giftIconSize = 30;
const double _underlineWidth = 26;
const double _underlineHeight = 3;
class RecommendTopNav extends StatelessWidget {
const RecommendTopNav({
@@ -21,6 +22,7 @@ class RecommendTopNav extends StatelessWidget {
required this.onSelected,
required this.onSearch,
this.onVideo = false,
this.onGift,
});
static const double height = _navHeight;
@@ -30,6 +32,9 @@ class RecommendTopNav extends StatelessWidget {
final VoidCallback onSearch;
final bool onVideo;
/// 右上角金色礼物盒(钱包入口);为空时不显示。
final VoidCallback? onGift;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
@@ -41,34 +46,16 @@ 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,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.feedPageHorizontal,
),
child: Stack(
alignment: Alignment.center,
children: [
FittedBox(
fit: BoxFit.scaleDown,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.only(left: 20, right: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -76,6 +63,7 @@ class RecommendTopNav extends StatelessWidget {
if (index > 0) const SizedBox(width: _tabGap),
_tab(
key: Key('recommend-tab-${items[index].$3}'),
code: items[index].$3,
label: items[index].$2,
selected: selected == items[index].$1,
shadows: shadows,
@@ -85,33 +73,53 @@ class RecommendTopNav extends StatelessWidget {
],
),
),
Align(
alignment: Alignment.centerRight,
child: SizedBox.square(
dimension: _searchHitSize,
child: IconButton(
key: const Key('recommend-search'),
tooltip: l10n.search,
onPressed: onSearch,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _searchHitSize,
height: _searchHitSize,
),
iconSize: _searchIconSize,
color: AppColors.textPrimary,
icon: const Icon(Icons.search_rounded),
),
SizedBox.square(
dimension: _searchHitSize,
child: IconButton(
key: const Key('recommend-search'),
tooltip: l10n.search,
onPressed: onSearch,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _searchHitSize,
height: _searchHitSize,
),
iconSize: _searchIconSize,
color: AppColors.textPrimary,
icon: const Icon(Icons.search_rounded),
),
),
if (onGift != null)
SizedBox.square(
dimension: _searchHitSize,
child: IconButton(
key: const Key('recommend-gift'),
tooltip: l10n.wallet,
onPressed: onGift,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _searchHitSize,
height: _searchHitSize,
),
iconSize: _giftIconSize,
icon: Image.asset(
'assets/icon/gift.png',
width: _giftIconSize,
height: _giftIconSize,
fit: BoxFit.contain,
),
),
),
],
),
const SizedBox(width: 8),
],
),
);
}
Widget _tab({
required Key key,
required String code,
required String label,
required bool selected,
required List<Shadow>? shadows,
@@ -121,23 +129,33 @@ class RecommendTopNav extends StatelessWidget {
key: key,
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: SizedBox(
height: height,
child: Center(
child: Text(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 补偿文字下方的 4pt 间距 + 3pt 下划线,让文字视觉中心与右侧图标对齐。
const SizedBox(height: 4 + _underlineHeight),
Text(
label,
maxLines: 1,
style: TextStyle(
color: selected
? AppColors.textPrimary
: AppColors.textTabInactive,
color: AppColors.textPrimary,
fontSize: _tabFont,
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
letterSpacing: 0,
shadows: shadows,
),
),
),
const SizedBox(height: 4),
Container(
key: Key('recommend-tab-$code-underline'),
width: _underlineWidth,
height: _underlineHeight,
decoration: BoxDecoration(
color: selected ? AppColors.brandRed : AppColors.transparent,
borderRadius: BorderRadius.circular(_underlineHeight / 2),
),
),
],
),
);
}
@@ -15,7 +15,6 @@ import '../../core/platform/haptics.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_theme.dart';
import '../../core/widgets/app_pull_to_refresh.dart';
import '../../core/widgets/auth_gate.dart';
import '../../core/widgets/empty_state.dart';
import '../../core/widgets/paged_list_footer.dart';
import '../../core/widgets/subpage_header.dart';
@@ -35,7 +34,6 @@ class WatchRecordsPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final signedIn = context.watch<AuthController>().isSignedIn;
final l10n = AppLocalizations.of(context)!;
return Theme(
data: AppTheme.dark(),
@@ -49,11 +47,7 @@ class WatchRecordsPage extends StatelessWidget {
title: l10n.watchHistory,
backKey: const Key('watch-records-back'),
),
Expanded(
child: signedIn
? const _WatchRecordsBody()
: const AuthGatePanel(),
),
Expanded(child: const _WatchRecordsBody()),
],
),
),
@@ -71,10 +65,15 @@ class _WatchRecordsBody extends StatefulWidget {
class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
late final WatchRecordsController controller;
late final AuthController _auth;
late bool _signedIn;
@override
void initState() {
super.initState();
_auth = context.read<AuthController>();
_signedIn = _auth.isSignedIn;
_auth.addListener(_handleAuthChanged);
controller = WatchRecordsBinding().create(
history: context.read<WatchHistoryRepository>(),
catalog: context.read<CatalogRepository>(),
@@ -82,8 +81,17 @@ class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
unawaited(controller.load());
}
void _handleAuthChanged() {
final signedIn = _auth.isSignedIn;
if (_signedIn == signedIn || !mounted) return;
_signedIn = signedIn;
controller.reset();
unawaited(controller.load());
}
@override
void dispose() {
_auth.removeListener(_handleAuthChanged);
controller.dispose();
super.dispose();
}
+20 -20
View File
@@ -216,7 +216,7 @@ packages:
source: hosted
version: "2.0.2"
html:
dependency: transitive
dependency: "direct main"
description:
name: html
sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699"
@@ -248,10 +248,10 @@ packages:
dependency: transitive
description:
name: intl
sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5"
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.20.2"
version: "0.20.3"
jni:
dependency: transitive
description:
@@ -328,10 +328,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -344,10 +344,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.18.0"
version: "1.19.0"
mime:
dependency: transitive
description:
@@ -380,14 +380,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.0.0"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790"
url: "https://pub.flutter-io.cn"
source: hosted
version: "7.1.0"
path:
dependency: transitive
description:
@@ -444,6 +436,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.3.0"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790"
url: "https://pub.flutter-io.cn"
source: hosted
version: "7.1.0"
platform:
dependency: transitive
description:
@@ -613,10 +613,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.7.11"
version: "0.7.12"
typed_data:
dependency: transitive
description:
@@ -637,10 +637,10 @@ packages:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d"
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.2.0"
version: "2.4.3"
video_player:
dependency: "direct main"
description:
@@ -730,5 +730,5 @@ packages:
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.12.2 <4.0.0"
dart: ">=3.13.0 <4.0.0"
flutter: ">=3.44.0"
+40
View File
@@ -0,0 +1,40 @@
// Author: fruit.com.cn
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/formatting/account_display.dart';
void main() {
test('should_localize_country_name', () {
expect(countryName('ID', 'zh'), '印度尼西亚');
expect(countryName('us', 'en'), 'United States');
expect(countryName('TH', 'id'), 'Thailand');
// 未收录的码原样返回,避免展示成空白
expect(countryName('ZZ', 'zh'), 'ZZ');
expect(countryName('', 'zh'), '');
});
test('should_localize_timezone_to_city', () {
expect(timezoneName('Asia/Jakarta', 'zh'), '雅加达');
expect(timezoneName('Asia/Jakarta', 'en'), 'Jakarta');
expect(
timezoneName('America/Argentina/Buenos_Aires', 'en'),
'Buenos Aires',
);
expect(timezoneName('', 'zh'), '');
});
test('should_localize_language_by_primary_tag', () {
expect(languageName('id-ID', 'zh'), '印度尼西亚语');
expect(languageName('zh-TW', 'en'), 'Chinese');
expect(languageName('en-US', 'id'), 'Inggris');
expect(languageName('', 'zh'), '');
});
test('should_localize_status_and_vip_level', () {
expect(accountStatusText('normal', 'zh'), '正常');
expect(accountStatusText('banned', 'id'), 'Diblokir');
expect(accountStatusText('weird', 'zh'), 'weird');
expect(vipLevelText(0, 'zh'), '未开通');
expect(vipLevelText(2, 'zh'), 'VIP 2');
});
}
+1 -1
View File
@@ -112,7 +112,7 @@ void main() {
final toast = find.byKey(const Key('centered-toast'));
expect(toast, findsOneWidget);
expect(find.text('Invalid email or password'), findsOneWidget);
expect(find.text('Sign in to continue'), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
expect(api.loginCalls, 1);
expect(
+2 -3
View File
@@ -14,7 +14,6 @@ import 'package:fruitshorts/core/data/services/auth_session_store.dart';
import 'package:fruitshorts/core/platform/haptics.dart';
import 'package:fruitshorts/core/theme/app_colors.dart';
import 'package:fruitshorts/core/theme/app_dimens.dart';
import 'package:fruitshorts/core/theme/app_theme.dart';
import 'package:fruitshorts/l10n/app_localizations.dart';
import 'package:fruitshorts/pages/auth/auth_view.dart';
@@ -136,7 +135,7 @@ void main() {
cardDecoration.borderRadius,
BorderRadius.circular(AppDimens.authCardRadius),
);
expect(cardDecoration.boxShadow, contains(AppTheme.cardShadow));
expect(cardDecoration.boxShadow, isNull);
expect(card.padding, const EdgeInsets.all(20));
final email = tester.widget<TextField>(
@@ -222,7 +221,7 @@ void main() {
find.descendant(of: back, matching: find.byType(Material)),
)
.color,
AppColors.card,
AppColors.transparent,
);
});
+20 -24
View File
@@ -135,7 +135,9 @@ void main() {
debugDefaultTargetPlatformOverride = null;
});
testWidgets('should_gate_guest_comment_input_without_focus', (tester) async {
testWidgets('should_open_guest_comment_composer_without_login', (
tester,
) async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
final repository = FakeCommentRepository(pages: [const CommentPage()]);
@@ -144,34 +146,20 @@ void main() {
final placeholder = find.byKey(const Key('comment-input-placeholder'));
expect(placeholder, findsOneWidget);
expect(find.text('Sign in to comment'), findsOneWidget);
await tester.tap(placeholder);
await tester.pumpAndSettle();
expect(find.text('Sign in to continue'), findsOneWidget);
await tester.tap(find.text('Not now'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('comment-composer-sheet')), findsNothing);
expect(placeholder, findsOneWidget);
expect(find.byKey(const Key('comment-composer-sheet')), findsOneWidget);
expect(find.byKey(const Key('auth-landing')), findsNothing);
});
testWidgets('should_focus_comment_input_after_successful_login', (
tester,
) async {
testWidgets('should_focus_guest_comment_input_immediately', (tester) async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
final repository = FakeCommentRepository(pages: [const CommentPage()]);
final auth = await _pumpSheet(tester, repository: repository);
await _pumpSheet(tester, repository: repository);
await tester.tap(find.byKey(const Key('comment-input-placeholder')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
await tester.tap(find.text('Sign In'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
(auth as _TestAuthController).setSignedIn(true);
await tester.pump();
Navigator.of(tester.element(find.byKey(const Key('auth-landing')))).pop();
await tester.pumpAndSettle();
expect(
@@ -218,9 +206,7 @@ void main() {
expect(multilineField.style?.height, 1.4);
});
testWidgets('should_gate_guest_post_without_creating_comment', (
tester,
) async {
testWidgets('should_publish_guest_comment_without_login', (tester) async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
final repository = FakeCommentRepository(pages: [const CommentPage()]);
@@ -229,8 +215,18 @@ void main() {
await tester.tap(find.byKey(const Key('comment-post')));
await tester.pumpAndSettle();
expect(find.text('Sign in to continue'), findsOneWidget);
expect(repository.publishCalls, isEmpty);
await tester.enterText(
find.byKey(const Key('comment-composer-input')),
'Guest comment',
);
await tester.pump();
await tester.tap(find.byKey(const Key('comment-composer-post')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('auth-landing')), findsNothing);
expect(repository.publishCalls, hasLength(1));
expect(repository.publishCalls.single.content, 'Guest comment');
expect(find.text('Guest comment'), findsOneWidget);
});
testWidgets('should_show_server_comments_and_append_next_cursor_page', (
+5 -1
View File
@@ -63,7 +63,11 @@ void main() {
});
test('should_use_the_configured_local_address_for_device_default', () {
expect(AppConfig.devHostBaseUrl, 'http://192.168.31.243:8081');
final uri = Uri.parse(AppConfig.devHostBaseUrl);
expect(uri.scheme, 'http');
expect(uri.host, isNotEmpty);
expect(uri.port, 8081);
expect(uri.path, isEmpty);
});
test('should_skip_probe_when_compiled_override_is_set', () async {
+1 -1
View File
@@ -43,7 +43,7 @@ void main() {
final scrollable = tester.state<ScrollableState>(
find.descendant(of: list, matching: find.byType(Scrollable)).first,
);
expect(scrollable.position.pixels, 0);
expect(scrollable.position.pixels, lessThan(0));
final indicator = find.byKey(const Key('pull-refresh-indicator'));
expect(indicator, findsOneWidget);
expect(
+81
View File
@@ -0,0 +1,81 @@
// Author: fruit.com.cn
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/data/services/auth_session_store.dart';
import 'package:fruitshorts/core/data/services/device_id_provider.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
/// 可控的系统设备标识来源。
class _FakeDeviceIdProvider implements DeviceIdProvider {
_FakeDeviceIdProvider(this.value, {this.region});
final String? value;
final String? region;
int calls = 0;
@override
Future<String?> systemDeviceId() async {
calls++;
return value;
}
@override
Future<String?> deviceRegion() async => region;
}
void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
});
test('should_prefer_system_device_id_over_local_value', () async {
final provider = _FakeDeviceIdProvider('a-9774d56d682e549c');
final store = AuthSessionStore(deviceIdProvider: provider);
expect(await store.deviceId(), 'a-9774d56d682e549c');
});
test('should_fall_back_to_stable_local_uuid_when_system_id_missing', () async {
final store = AuthSessionStore(
deviceIdProvider: _FakeDeviceIdProvider(null),
);
final first = await store.deviceId();
final second = await store.deviceId();
// 同一次运行内固定,且符合 UUIDv4 形态
expect(first, second);
expect(first, startsWith('d-'));
expect(
RegExp(
r'^d-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',
).hasMatch(first),
isTrue,
reason: '本地兜底必须是 UUIDv4,避免 32 位随机带来的碰撞',
);
});
test('should_cache_system_id_within_one_session', () async {
final provider = _FakeDeviceIdProvider('i-E621E1F8-C36C-495A-93FC-0C247A3E6E5F');
final store = AuthSessionStore(deviceIdProvider: provider);
await store.deviceId();
await store.deviceId();
expect(provider.calls, 1);
});
test('should_return_device_region_or_empty_string', () async {
final store = AuthSessionStore(
deviceIdProvider: _FakeDeviceIdProvider(null, region: 'TH'),
);
final missing = AuthSessionStore(
deviceIdProvider: _FakeDeviceIdProvider(null),
);
expect(await store.deviceRegion(), 'TH');
expect(await missing.deviceRegion(), '');
});
}
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff. Show more