Compare commits
105
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70be941755 | ||
|
|
351d0afd09 | ||
|
|
7d32324a2d | ||
|
|
1d4ab5e0e6 | ||
|
|
799f3d1b7d | ||
|
|
08aa6903d2 | ||
|
|
4de9417e27 | ||
|
|
e269d5dce5 | ||
|
|
78f464f2a4 | ||
|
|
9983d42015 | ||
|
|
bfe0df62dc | ||
|
|
df2654c9d6 | ||
|
|
496b1cb797 | ||
|
|
85dedf20fa | ||
|
|
43e60e29ec | ||
|
|
5346be40a9 | ||
|
|
de7da64886 | ||
|
|
709972245f | ||
|
|
d5d13549f5 | ||
|
|
c027acc91f | ||
|
|
a3f3481f4f | ||
|
|
1b19513efb | ||
|
|
935de13343 | ||
|
|
01a3b0101e | ||
|
|
d6df5fbe5f | ||
|
|
929b7f72f8 | ||
|
|
e028ca40b1 | ||
|
|
d206465ee1 | ||
|
|
9117bf58b8 | ||
|
|
bd826a9236 | ||
|
|
a5dbae7fff | ||
|
|
00405d2e3b | ||
|
|
72dcb92aca | ||
|
|
8d511933df | ||
|
|
06a2f6d7c0 | ||
|
|
0d785bf1f8 | ||
|
|
4c3acb047c | ||
|
|
d3dbc9f8dc | ||
|
|
4b97f89c0b | ||
|
|
6be024f86f | ||
|
|
6512808506 | ||
|
|
2d65cd3006 | ||
|
|
391b01e9d0 | ||
|
|
d4ce3a5d8b | ||
|
|
bf47c065c9 | ||
|
|
c6b3ca9311 | ||
|
|
a3d50eb935 | ||
|
|
188811fde6 | ||
|
|
37353dac15 | ||
|
|
350d16db75 | ||
|
|
76429628ec | ||
|
|
0f27daf664 | ||
|
|
afdc4af2f2 | ||
|
|
1b50a73bfc | ||
|
|
978c309cd7 | ||
|
|
c0f65042e6 | ||
|
|
a7d01e0306 | ||
|
|
ed2cf4c18c | ||
|
|
db3e153409 | ||
|
|
810ca5bf9d | ||
|
|
84b24775d6 | ||
|
|
9039b27c7f | ||
|
|
30b43878ab | ||
|
|
e7afd316f8 | ||
|
|
f3dd4a9b5c | ||
|
|
94b37ef00f | ||
|
|
bea50ab32f | ||
|
|
63296d2a92 | ||
|
|
b291044acc | ||
|
|
ee4e573f4f | ||
|
|
e8f192ccf8 | ||
|
|
c8ec481fc9 | ||
|
|
1fc8c4924e | ||
|
|
55fc2796a9 | ||
|
|
4d3d067f77 | ||
|
|
bb2c729a7e | ||
|
|
54eb5a60a8 | ||
|
|
6667330ce0 | ||
|
|
440188f261 | ||
|
|
9d2d3b97a1 | ||
|
|
23e80dd637 | ||
|
|
ab4c246675 | ||
|
|
2a32dec183 | ||
|
|
5dafc68775 | ||
|
|
80c962a95c | ||
|
|
2fef7470e0 | ||
|
|
0cb0ab0613 | ||
|
|
70d8e0f982 | ||
|
|
48b4e67d34 | ||
|
|
a3a79f7068 | ||
|
|
04f034817c | ||
|
|
516593499c | ||
|
|
df36890b48 | ||
|
|
222bacdeeb | ||
|
|
43f3593218 | ||
|
|
b83b5799e3 | ||
|
|
d4ae8f427f | ||
|
|
0eca7ecc31 | ||
|
|
98d7debfb5 | ||
|
|
b5e9deb4bd | ||
|
|
af5d8f9d80 | ||
|
|
47df002d8e | ||
|
|
4f1feeadbd | ||
|
|
8b50b5bd06 | ||
|
|
b84a5368d6 |
No files matched your search
@@ -1,18 +1,22 @@
|
||||
# FruitShorts(ReelShort)客户端
|
||||
|
||||
FruitShorts 是面向印尼市场的短剧 Flutter 客户端。当前版本已连接
|
||||
`FruitServer` 的 `/app/**` 接口,支持沉浸播放、找剧、账号、观看记录、收藏、
|
||||
下载授权、评论互动、站内通知和中英印尼三语界面。
|
||||
FruitShorts 是面向印尼市场的短剧 Flutter 客户端,已连接 `FruitServer` 的
|
||||
`/app/**` 接口。功能覆盖:四 tab 主页(推荐视频流 / 找剧 / 追剧 / 我的)、
|
||||
沉浸式播放与全屏剧集播放器、清晰度切换、剧单与排行榜、新剧页、搜索、观看记录、
|
||||
收藏短剧、评论与点赞、站内通知、钱包与商品、下载落盘与离线播放、中英印尼三语,
|
||||
以及 Android / iOS 双端画中画(退到后台自动进小窗)。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- Flutter 3.47.7 / Dart 3.13.5
|
||||
- Flutter 3.47.7 / Dart 3.13.5(`environment.sdk: ^3.12.2`)
|
||||
- Provider 状态管理与依赖注入
|
||||
- dio 网络请求
|
||||
- video_player 播放
|
||||
- shared_preferences 与 `SharedPreferencesAsync` 本地配置
|
||||
- path_provider + dart:io 下载落盘(先写 `.part`,完成后原子改名)
|
||||
- flutter_localizations,支持 `en`、`zh`、`id`
|
||||
- Android 系统画中画
|
||||
- 画中画:Android 用 `floating` + `permission_handler`(需悬浮窗权限);
|
||||
iOS 用原生 `AVPictureInPictureController` + 影子播放器(`ios/Runner/AppDelegate.swift`)
|
||||
|
||||
## 目录结构
|
||||
|
||||
@@ -22,7 +26,7 @@ lib/
|
||||
config/ 地址、语言和运行时配置
|
||||
data/ models、remote API、repository、controller
|
||||
formatting/ 文案与日期格式化
|
||||
platform/ 触觉等平台能力
|
||||
platform/ 平台能力:画中画通道、设备号、触觉
|
||||
theme/ 颜色与主题
|
||||
widgets/ 跨页面复用组件
|
||||
l10n/ 三语 ARB 与生成代码
|
||||
@@ -36,20 +40,21 @@ assets/ 图标、图片和本地媒体文件
|
||||
|
||||
## 已接接口
|
||||
|
||||
以下接口均在 `lib/core/data/remote/` 中有实际调用,共 26 个不同路径、
|
||||
31 个 HTTP 方法级调用。
|
||||
以下接口均在 `lib/core/data/remote/` 中有实际调用,共 47 个不同路径。
|
||||
|
||||
| 分组 | 契约 | 接口 |
|
||||
| --- | --- | --- |
|
||||
| 账号 | §1.1 | `POST /app/auth/register`、`/login`、`/refresh`、`/logout` |
|
||||
| 内容 | §1.3、§1.4 | `GET /app/home/feed`、`/app/discover/feed`、`/app/categories`、`/app/dramas/{id}`、`/app/episodes/{id}/play` |
|
||||
| 观看记录 | §1.5 | `POST/GET /app/watch/progress`、`GET /app/watch/recent`、`DELETE /app/watch/progress/{dramaId}`、`DELETE /app/watch/progress` |
|
||||
| 收藏 | §1.5 | `POST /app/favorites/toggle`、`GET /app/favorites`、`DELETE /app/favorites/{dramaId}` |
|
||||
| 下载授权 | §1.6 | `GET /app/downloads/policy`、`PUT /app/downloads/settings`、`POST/GET /app/downloads`、`GET /app/downloads/{episodeId}/url`、`POST /app/downloads/{episodeId}/progress`、`DELETE /app/downloads/{episodeId}`、`DELETE /app/downloads` |
|
||||
| 互动 | §1.7 | `GET/POST /app/comments`、`DELETE /app/comments/{id}`、`POST /app/likes/toggle`、`POST /app/reports` |
|
||||
| 公告 | §1.9.2 | `GET /app/notices` |
|
||||
| 分组 | 接口 |
|
||||
| --- | --- |
|
||||
| 账号 | `POST /app/auth/register`、`/login`、`/refresh`、`/logout`、`/otp`;`GET /app/me`、`/app/me/devices`、`/app/me/export`;`POST /app/me/deactivate`、`/app/me/deactivate/cancel` |
|
||||
| 内容 | `GET /app/home/feed`、`/app/feed`、`/app/discover/feed`、`/app/categories`、`/app/categories/{id}/dramas`、`/app/drama-categories`、`/app/dramas/page`、`/app/dramas/{id}`、`/app/tags`、`/app/search`、`/app/playlists`、`/app/playlists/{id}` |
|
||||
| 播放 | `GET /app/episodes/{id}/play`、`/app/episodes/{id}/stats`;`POST /app/episodes/{id}/unlock` |
|
||||
| 观看记录 | `POST/GET /app/watch/progress`、`GET /app/watch/recent`、`DELETE /app/watch/progress/{dramaId}`、`DELETE /app/watch/progress` |
|
||||
| 收藏 | `POST /app/favorites/toggle`、`GET /app/favorites`、`DELETE /app/favorites/{dramaId}`、`POST /app/favorites/remove` |
|
||||
| 下载 | `GET /app/downloads/policy`、`PUT /app/downloads/settings`、`POST/GET /app/downloads`、`GET /app/downloads/{id}/url`、`POST /app/downloads/{id}/progress`、`DELETE /app/downloads/{id}`、`DELETE /app/downloads` |
|
||||
| 互动 | `GET/POST /app/comments`、`DELETE /app/comments/{id}`、`GET /app/comments/count`、`POST /app/likes/toggle`、`POST /app/reports` |
|
||||
| 商业化 | `GET /app/wallet`、`/app/products`、`/app/orders` |
|
||||
| 公告 | `GET /app/notices` |
|
||||
|
||||
客户端没有调用 `/app/config` 或创作者入驻接口。
|
||||
客户端没有调用 `/app/config` 和创作者入驻接口。
|
||||
|
||||
## 运行
|
||||
|
||||
@@ -90,15 +95,30 @@ flutter run -d <udid> \
|
||||
|
||||
### Debug 运行时地址
|
||||
|
||||
debug 版本可在「我的 → 设置 → 服务器地址」修改后端地址,保存后重启 App 生效。
|
||||
地址优先级:
|
||||
debug 包在找剧页加载失败时会显示调试条,点其中的「修改服务器地址」可直接改成
|
||||
当前电脑 IP,保存后立即重载,不用重新打包。地址优先级:
|
||||
|
||||
```text
|
||||
本地运行时设置 > --dart-define(API_BASE_URL) > 平台默认地址
|
||||
本地运行时设置 > --dart-define(API_BASE_URL) > AppConfig.defaultBaseUrl
|
||||
```
|
||||
|
||||
因此不带 `--dart-define` 构建的 debug APK 也可在安装后改成当前电脑 IP。
|
||||
release 版本不显示入口,也不会读取本地覆盖。
|
||||
`devHostBaseUrl` 默认写死为 `http://192.168.31.243:8081`
|
||||
(`lib/core/config/app_config.dart`)。debug 包启动时按
|
||||
「环回 `127.0.0.1` → `devHostBaseUrl` → 公网」顺序探测可用地址;release 包不探测,
|
||||
固定使用公网地址。换 Wi-Fi、路由器换网段后 `devHostBaseUrl` 会失效,此时要么传
|
||||
`--dart-define`,要么改这个常量。release 包不显示地址入口,也不读取本地覆盖。
|
||||
|
||||
## 画中画
|
||||
|
||||
| 平台 | 行为 |
|
||||
| --- | --- |
|
||||
| Android | 首次点播放页小窗按钮时申请悬浮窗权限;授权后退出 App 自动进入系统小窗。沉浸流与独立播放页共用一份引用计数,任一处活跃都算「在播」,避免互相顶掉 |
|
||||
| iOS | 原生影子播放器承载 `AVPictureInPictureController`,只有播放页处于活跃状态时退到后台才自动进小窗;停在剧单等页面退后台不会触发 |
|
||||
|
||||
- 小窗内切集直接换源,不走页面翻页,可连续自动播放
|
||||
- iOS 从系统小窗还原时用原生过渡层盖住纹理黑帧,等首帧就绪后再淡出
|
||||
- 播放页「更多」面板里有「退出自动小窗」开关(仅支持自动小窗的平台显示),关掉后
|
||||
退到后台不再进入小窗
|
||||
|
||||
## 环境注意
|
||||
|
||||
@@ -156,21 +176,35 @@ flutter build apk --release --target-platform android-arm64,android-arm
|
||||
- 不要直接运行 `flutter build apk --release`:默认会编译三套原生库,包体约 57MB。
|
||||
- 只有需要进一步压缩单机下载体积时,才考虑 `--split-per-abi` 出分架构包(arm64 约 21MB、armv7 约 19MB),默认不用。
|
||||
|
||||
## 生产打包(iOS)
|
||||
|
||||
```bash
|
||||
# 正式签名(需要 iOS Distribution 证书 + App Store 描述文件)
|
||||
flutter build ipa --release
|
||||
|
||||
# 只有 Apple Development 证书时:出开发签名 IPA,只能装已注册设备
|
||||
flutter build ipa --release --export-method development
|
||||
```
|
||||
|
||||
产物在 `build/ios/ipa/*.ipa`。画中画依赖 `UIBackgroundModes` 里的 `audio` 与
|
||||
`AVPictureInPictureController`,改动 `ios/Runner/Info.plist` 或 `AppDelegate.swift`
|
||||
后要重新构建,热重载不会生效。
|
||||
|
||||
## 门禁
|
||||
|
||||
```bash
|
||||
dart analyze lib test
|
||||
dart analyze
|
||||
flutter test
|
||||
flutter build apk --debug
|
||||
```
|
||||
|
||||
测试文件按模块放在 `test/` 下,用例名使用
|
||||
当前基线:`dart analyze` 仅 1 条既存 info(`intl` 未在 `pubspec.yaml` 声明);
|
||||
`flutter test` 全量 775 例通过。测试文件按模块放在 `test/` 下,用例名使用
|
||||
`should_<期望>_when_<条件>`。真实后端联调测试在服务未启动时会跳过。
|
||||
|
||||
## 当前边界
|
||||
|
||||
- 下载仅管理服务端授权,不落盘、不续传、不支持离线播放。
|
||||
- 没有独立搜索接口,搜索能力尚未形成完整闭环。
|
||||
- 下载会落盘并支持离线播放,但不支持断点续传:中途失败会丢弃 `.part` 重下。
|
||||
- 支付与金币:客户端已有钱包、商品、下单接口与页面,商店票据校验依赖服务端配置凭据。
|
||||
- 站内通知没有已读/未读和红点状态。
|
||||
- 支付、金币和会员权益尚未形成客户端闭环。
|
||||
- Android 支持系统画中画;iOS 画中画尚未接入。
|
||||
- 播放清晰度切换会保留旧画面 500ms 掩盖闪屏,切换瞬间的进度以相对位置续播。
|
||||
@@ -1,4 +1,5 @@
|
||||
/.gradle
|
||||
/build/
|
||||
/captures/
|
||||
/local.properties
|
||||
GeneratedPluginRegistrant.java
|
||||
|
||||
@@ -8,7 +8,9 @@ plugins {
|
||||
|
||||
android {
|
||||
namespace = "com.stormg.lumadrama"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
// permission_handler_android 14 的 AAR 元数据要求依赖方 compileSdk >= 37,
|
||||
// 固定为 37(比 Flutter 默认的 36 高一档,只影响编译期 API 可见性)。
|
||||
compileSdk = 37
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission
|
||||
android:name="android.permission.INTERNET"/>
|
||||
<!-- 画中画自动触发依赖的「显示在其他应用上层」权限(部分 ROM 用它管控 PiP) -->
|
||||
<uses-permission
|
||||
android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
|
||||
<application
|
||||
android:label="FruitShorts"
|
||||
android:name="${applicationName}"
|
||||
|
||||
@@ -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
|
||||
@@ -241,6 +284,7 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FruitPip"
|
||||
private const val thumbnailMaxWidth = 240
|
||||
private const val thumbnailJpegQuality = 70
|
||||
private const val thumbnailTimeoutMs = 1500L
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
|
||||
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
|
||||
8C4E1A022F9A4B1000C636F3 /* WirelessDataPrompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */; };
|
||||
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
||||
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
|
||||
@@ -49,6 +50,7 @@
|
||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
|
||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WirelessDataPrompt.swift; sourceTree = "<group>"; };
|
||||
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
|
||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
|
||||
@@ -122,6 +124,7 @@
|
||||
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
|
||||
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
|
||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
|
||||
8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */,
|
||||
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
|
||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
|
||||
);
|
||||
@@ -282,6 +285,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
|
||||
8C4E1A022F9A4B1000C636F3 /* WirelessDataPrompt.swift in Sources */,
|
||||
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
|
||||
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Flutter
|
||||
import UIKit
|
||||
import AVFoundation
|
||||
import AVKit
|
||||
|
||||
private let thumbnailHTTPHeaderFieldsKey = "AVURLAssetHTTPHeaderFieldsKey"
|
||||
|
||||
@@ -35,8 +36,321 @@ final class RunnerFlutterViewController: FlutterViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// iOS 影子播放器:独立 AVPlayer + AVPlayerLayer 专供画中画窗口。
|
||||
/// Flutter 的 video_player 走纹理渲染,没有 AVPlayerLayer,无法直接创建
|
||||
/// AVPictureInPictureController;小窗的画面与声音由影子接管,退出时把
|
||||
/// 影子进度回传给 Dart,由 Flutter 播放器 seek 对齐后继续。
|
||||
final class PipShadowCoordinator: NSObject, AVPictureInPictureControllerDelegate {
|
||||
static let shared = PipShadowCoordinator()
|
||||
|
||||
private var player: AVPlayer?
|
||||
private var playerLayer: AVPlayerLayer?
|
||||
private var controller: AVPictureInPictureController?
|
||||
private var endObserver: NSObjectProtocol?
|
||||
private var possibleObservation: NSKeyValueObservation?
|
||||
/// 画中画还原过渡层:原生窗口级红晕渐变,在系统还原动画开始时立即盖上,
|
||||
/// 避免回前台瞬间 Flutter 表面未恢复显示黑帧;视频出帧后由 Dart 通知淡出。
|
||||
private var restoreOverlay: UIView?
|
||||
/// 系统要求 playerLayer 位于真实的 view 层级中才会判定画中画可用,
|
||||
/// 因此用 1x1 透明宿主 view 承载,而不是直接挂在 window.layer 上。
|
||||
private var hostView: UIView?
|
||||
/// 影子图层就绪稍晚于创建,置位后由 KVO 自动拉起画中画。
|
||||
private var pendingStart = false
|
||||
private var startRetryWorkItems: [DispatchWorkItem] = []
|
||||
|
||||
weak var channel: FlutterMethodChannel?
|
||||
|
||||
/// active 变化回调;停止时把影子最终进度(毫秒)一并提供。
|
||||
var onPipChanged: ((Bool, Int64) -> Void)?
|
||||
/// 影子在画中画里播完当前集。
|
||||
var onPlaybackEnded: (() -> Void)?
|
||||
|
||||
static var isSupported: Bool {
|
||||
AVPictureInPictureController.isPictureInPictureSupported()
|
||||
}
|
||||
|
||||
private var keyWindow: UIWindow? {
|
||||
UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.flatMap { $0.windows }
|
||||
.first { $0.isKeyWindow }
|
||||
}
|
||||
|
||||
/// 首次创建影子:1x1 图层挂在 keyWindow 的宿主 view 里(肉眼不可见),静音待命。
|
||||
/// [autoEnter] 为 true 时退后台由系统自动拉起画中画(需影子在播,见 armAutoEnter)。
|
||||
func prepare(urlString: String, positionMs: Int64, autoEnter: Bool) {
|
||||
teardown()
|
||||
log("prepare begin supported=\(PipShadowCoordinator.isSupported) autoEnter=\(autoEnter)")
|
||||
guard Self.isSupported else { return }
|
||||
guard let url = URL(string: urlString) else {
|
||||
log("prepare failed bad url \(urlString)")
|
||||
return
|
||||
}
|
||||
guard let window = keyWindow else {
|
||||
log("prepare failed no key window")
|
||||
return
|
||||
}
|
||||
let item = AVPlayerItem(url: url)
|
||||
let p = AVPlayer(playerItem: item)
|
||||
p.isMuted = true
|
||||
p.actionAtItemEnd = .pause
|
||||
let layer = AVPlayerLayer()
|
||||
layer.player = p
|
||||
let host = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
|
||||
host.isUserInteractionEnabled = false
|
||||
host.backgroundColor = .clear
|
||||
window.addSubview(host)
|
||||
layer.frame = host.bounds
|
||||
host.layer.addSublayer(layer)
|
||||
hostView = host
|
||||
guard let c = AVPictureInPictureController(playerLayer: layer) else {
|
||||
p.pause()
|
||||
log("prepare failed no pip controller")
|
||||
return
|
||||
}
|
||||
c.canStartPictureInPictureAutomaticallyFromInline = autoEnter
|
||||
c.delegate = self
|
||||
player = p
|
||||
playerLayer = layer
|
||||
controller = c
|
||||
// 静音起播让 item 完成首帧解码,isPictureInPicturePossible 才会变 true。
|
||||
p.play()
|
||||
possibleObservation = c.observe(
|
||||
\.isPictureInPicturePossible,
|
||||
options: [.new, .initial]
|
||||
) { [weak self] controller, change in
|
||||
let value = change.newValue ?? controller.isPictureInPicturePossible
|
||||
self?.log("possible changed to \(value)")
|
||||
guard let self, self.pendingStart, controller.isPictureInPicturePossible else { return }
|
||||
self.pendingStart = false
|
||||
// 刚翻 true 的同一 runloop 里调用会被系统静默拒绝,推到下一拍再进。
|
||||
DispatchQueue.main.async {
|
||||
guard self.controller === controller, controller.isPictureInPicturePossible else {
|
||||
self.log("start via kvo aborted (shadow replaced)")
|
||||
return
|
||||
}
|
||||
self.log("start via kvo")
|
||||
controller.startPictureInPicture()
|
||||
}
|
||||
}
|
||||
log("shadow ready, seeking to \(positionMs)ms")
|
||||
if positionMs > 0 {
|
||||
p.seek(
|
||||
to: CMTime(value: positionMs, timescale: 1000),
|
||||
toleranceBefore: .zero,
|
||||
toleranceAfter: .zero
|
||||
)
|
||||
}
|
||||
registerEndObserver(for: item)
|
||||
activateAudioSession()
|
||||
}
|
||||
|
||||
/// 退出 App 前(inactive)把影子对齐到当前进度并静音起播:
|
||||
/// auto PiP 只在「player 正在播放 + 图层离屏」时由系统触发。
|
||||
func armAutoEnter(positionMs: Int64) {
|
||||
guard let player, let controller else {
|
||||
log("arm failed, shadow missing")
|
||||
return
|
||||
}
|
||||
guard controller.canStartPictureInPictureAutomaticallyFromInline else {
|
||||
log("arm failed, autoEnter disabled on shadow")
|
||||
return
|
||||
}
|
||||
log("arm auto enter at \(positionMs)ms")
|
||||
if positionMs > 0 {
|
||||
player.seek(
|
||||
to: CMTime(value: positionMs, timescale: 1000),
|
||||
toleranceBefore: CMTime(value: 800, timescale: 1000),
|
||||
toleranceAfter: CMTime(value: 800, timescale: 1000)
|
||||
)
|
||||
}
|
||||
player.play()
|
||||
}
|
||||
|
||||
/// 回前台后取消待命:影子暂停回静音,等待下一次退后台。
|
||||
func disarmAutoEnter() {
|
||||
guard let player else { return }
|
||||
log("disarm auto enter")
|
||||
player.pause()
|
||||
player.isMuted = true
|
||||
}
|
||||
|
||||
/// 进入画中画:图层就绪则立即进入,否则 KVO/延时重试在就绪后自动进入。
|
||||
/// 仅当影子从未创建成功(prepare 失败)时返回 false。
|
||||
func start() -> Bool {
|
||||
guard let controller else {
|
||||
log("start failed, shadow not created")
|
||||
return false
|
||||
}
|
||||
log("start requested possible=\(controller.isPictureInPicturePossible)")
|
||||
pendingStart = true
|
||||
if controller.isPictureInPicturePossible {
|
||||
pendingStart = false
|
||||
controller.startPictureInPicture()
|
||||
}
|
||||
scheduleStartRetries()
|
||||
return true
|
||||
}
|
||||
|
||||
/// KVO 偶发不触发或流加载较慢时兜底:就绪后再试两次。
|
||||
private func scheduleStartRetries() {
|
||||
startRetryWorkItems.forEach { $0.cancel() }
|
||||
startRetryWorkItems.removeAll()
|
||||
for delay in [1.0, 2.5] {
|
||||
let item = DispatchWorkItem { [weak self] in
|
||||
guard
|
||||
let self,
|
||||
self.pendingStart,
|
||||
let controller = self.controller,
|
||||
controller.isPictureInPicturePossible
|
||||
else { return }
|
||||
self.log("start via retry after \(delay)s")
|
||||
self.pendingStart = false
|
||||
controller.startPictureInPicture()
|
||||
}
|
||||
startRetryWorkItems.append(item)
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
|
||||
}
|
||||
}
|
||||
|
||||
/// 画中画内换集:只换 AVPlayerItem,不动 player/layer,窗口不中断。
|
||||
func replaceItem(urlString: String, positionMs: Int64) {
|
||||
guard let player, let url = URL(string: urlString) else { return }
|
||||
let item = AVPlayerItem(url: url)
|
||||
player.replaceCurrentItem(with: item)
|
||||
registerEndObserver(for: item)
|
||||
if positionMs > 0 {
|
||||
player.seek(
|
||||
to: CMTime(value: positionMs, timescale: 1000),
|
||||
toleranceBefore: .zero,
|
||||
toleranceAfter: .zero
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 进入画中画后解除静音并起播(此时 Flutter 播放器已被暂停)。
|
||||
func unmuteAndPlay() {
|
||||
player?.isMuted = false
|
||||
player?.play()
|
||||
}
|
||||
|
||||
func positionMs() -> Int64 {
|
||||
Int64(max(0, player?.currentTime().seconds ?? 0) * 1000)
|
||||
}
|
||||
|
||||
func stopPip() {
|
||||
controller?.stopPictureInPicture()
|
||||
}
|
||||
|
||||
func teardown() {
|
||||
startRetryWorkItems.forEach { $0.cancel() }
|
||||
startRetryWorkItems.removeAll()
|
||||
possibleObservation?.invalidate()
|
||||
possibleObservation = nil
|
||||
pendingStart = false
|
||||
if let endObserver {
|
||||
NotificationCenter.default.removeObserver(endObserver)
|
||||
}
|
||||
endObserver = nil
|
||||
player?.pause()
|
||||
player?.replaceCurrentItem(with: nil)
|
||||
playerLayer?.removeFromSuperlayer()
|
||||
playerLayer = nil
|
||||
hostView?.removeFromSuperview()
|
||||
hostView = nil
|
||||
controller?.delegate = nil
|
||||
controller = nil
|
||||
player = nil
|
||||
}
|
||||
|
||||
/// 诊断日志:NSLog 之外同步转发到 Dart,便于在 flutter run 控制台观察。
|
||||
private func log(_ message: String) {
|
||||
NSLog("pip: %@", message)
|
||||
channel?.invokeMethod("pipDebug", arguments: message)
|
||||
}
|
||||
|
||||
private func registerEndObserver(for item: AVPlayerItem) {
|
||||
if let endObserver {
|
||||
NotificationCenter.default.removeObserver(endObserver)
|
||||
}
|
||||
endObserver = NotificationCenter.default.addObserver(
|
||||
forName: .AVPlayerItemDidPlayToEndTime,
|
||||
object: item,
|
||||
queue: .main
|
||||
) { [weak self] _ in
|
||||
self?.log("item did play to end")
|
||||
self?.onPlaybackEnded?()
|
||||
}
|
||||
}
|
||||
|
||||
/// 画中画的声音走影子播放器,需要 playback 类别的音频会话保活。
|
||||
private func activateAudioSession() {
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
} catch {
|
||||
// 会话激活失败只影响后台出声,不阻断画中画。
|
||||
}
|
||||
}
|
||||
|
||||
func pictureInPictureControllerWillStartPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
log("will start")
|
||||
pendingStart = false
|
||||
onPipChanged?(true, 0)
|
||||
}
|
||||
|
||||
func pictureInPictureControllerWillStopPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
log("will stop, showing restore overlay")
|
||||
showRestoreOverlay()
|
||||
}
|
||||
|
||||
func pictureInPictureControllerDidStopPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
log("did stop")
|
||||
showRestoreOverlay()
|
||||
onPipChanged?(false, positionMs())
|
||||
}
|
||||
|
||||
/// 盖原生过渡层(幂等):主题红晕渐变,不依赖 Flutter 渲染。
|
||||
func showRestoreOverlay() {
|
||||
guard let window = keyWindow else { return }
|
||||
restoreOverlay?.removeFromSuperview()
|
||||
let overlay = UIView(frame: window.bounds)
|
||||
overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
let gradient = CAGradientLayer()
|
||||
gradient.frame = overlay.bounds
|
||||
gradient.colors = [
|
||||
UIColor(red: 0.298, green: 0.086, blue: 0.102, alpha: 1).cgColor,
|
||||
UIColor(red: 0.118, green: 0.043, blue: 0.047, alpha: 1).cgColor,
|
||||
UIColor(red: 0.063, green: 0.063, blue: 0.071, alpha: 1).cgColor,
|
||||
]
|
||||
gradient.locations = [0, 0.22, 0.62]
|
||||
gradient.startPoint = CGPoint(x: 0.5, y: 0)
|
||||
gradient.endPoint = CGPoint(x: 0.5, y: 1)
|
||||
overlay.layer.addSublayer(gradient)
|
||||
window.addSubview(overlay)
|
||||
restoreOverlay = overlay
|
||||
}
|
||||
|
||||
/// 淡出并移除过渡层(视频首帧已确认后由 Dart 调用)。
|
||||
func hideRestoreOverlay() {
|
||||
guard let overlay = restoreOverlay else { return }
|
||||
restoreOverlay = nil
|
||||
UIView.animate(
|
||||
withDuration: 0.25,
|
||||
animations: { overlay.alpha = 0 }
|
||||
) { _ in overlay.removeFromSuperview() }
|
||||
}
|
||||
}
|
||||
|
||||
@main
|
||||
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
||||
private let wirelessDataPrompt = WirelessDataPrompt()
|
||||
private let thumbnailQueue = DispatchQueue(
|
||||
label: "com.stormg.lumadrama.thumbnail",
|
||||
qos: .userInitiated
|
||||
@@ -50,8 +364,20 @@ final class RunnerFlutterViewController: FlutterViewController {
|
||||
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
||||
}
|
||||
|
||||
override func applicationDidBecomeActive(_ application: UIApplication) {
|
||||
super.applicationDidBecomeActive(application)
|
||||
requestWirelessDataPrompt()
|
||||
}
|
||||
|
||||
func requestWirelessDataPrompt() {
|
||||
wirelessDataPrompt.requestSystemPrompt()
|
||||
}
|
||||
|
||||
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
||||
registerWirelessDataChannel(engineBridge)
|
||||
registerDeviceIdChannel(engineBridge)
|
||||
registerPipChannel(engineBridge)
|
||||
let channel = FlutterMethodChannel(
|
||||
name: "com.stormg.lumadrama/share",
|
||||
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
||||
@@ -132,4 +458,130 @@ final class RunnerFlutterViewController: FlutterViewController {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// iOS 画中画:影子播放器通道,与 Android 共用同一 channel 名。
|
||||
private func registerPipChannel(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||
let channel = FlutterMethodChannel(
|
||||
name: "com.stormg.lumadrama/pip",
|
||||
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
||||
)
|
||||
let pip = PipShadowCoordinator.shared
|
||||
pip.channel = channel
|
||||
channel.setMethodCallHandler { call, result in
|
||||
switch call.method {
|
||||
case "isAvailable":
|
||||
result(PipShadowCoordinator.isSupported)
|
||||
case "enter":
|
||||
guard let args = call.arguments as? [String: Any],
|
||||
let url = args["url"] as? String else {
|
||||
result(false)
|
||||
return
|
||||
}
|
||||
let positionMs = (args["positionMs"] as? NSNumber)?.int64Value ?? 0
|
||||
pip.prepare(urlString: url, positionMs: positionMs, autoEnter: false)
|
||||
// 等一拍让 AVPlayerLayer 完成挂载再请求进入画中画。
|
||||
DispatchQueue.main.async {
|
||||
result(pip.start())
|
||||
}
|
||||
case "prepareShadow":
|
||||
guard let args = call.arguments as? [String: Any],
|
||||
let url = args["url"] as? String else {
|
||||
result(nil)
|
||||
return
|
||||
}
|
||||
pip.prepare(
|
||||
urlString: url,
|
||||
positionMs: (args["positionMs"] as? NSNumber)?.int64Value ?? 0,
|
||||
autoEnter: (args["autoEnter"] as? NSNumber)?.boolValue ?? false
|
||||
)
|
||||
result(nil)
|
||||
case "armAutoEnter":
|
||||
pip.armAutoEnter(
|
||||
positionMs: (call.arguments as? [String: Any])?["positionMs"] as? Int64 ?? 0
|
||||
)
|
||||
result(nil)
|
||||
case "showRestoreOverlay":
|
||||
pip.showRestoreOverlay()
|
||||
result(nil)
|
||||
case "hideRestoreOverlay":
|
||||
pip.hideRestoreOverlay()
|
||||
result(nil)
|
||||
case "disarmAutoEnter":
|
||||
pip.disarmAutoEnter()
|
||||
result(nil)
|
||||
case "unmute":
|
||||
pip.unmuteAndPlay()
|
||||
result(nil)
|
||||
case "replaceItem":
|
||||
guard let args = call.arguments as? [String: Any],
|
||||
let url = args["url"] as? String else {
|
||||
result(nil)
|
||||
return
|
||||
}
|
||||
pip.replaceItem(
|
||||
urlString: url,
|
||||
positionMs: (args["positionMs"] as? NSNumber)?.int64Value ?? 0
|
||||
)
|
||||
result(nil)
|
||||
case "stop":
|
||||
pip.stopPip()
|
||||
result(nil)
|
||||
case "teardown":
|
||||
pip.teardown()
|
||||
result(nil)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
pip.onPipChanged = { active, positionMs in
|
||||
channel.invokeMethod(
|
||||
"onPipChanged",
|
||||
arguments: ["active": active, "positionMs": positionMs]
|
||||
)
|
||||
}
|
||||
pip.onPlaybackEnded = {
|
||||
channel.invokeMethod("onPipPlaybackEnded", arguments: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// 设备标识: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,
|
||||
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
||||
)
|
||||
channel.setMethodCallHandler { [weak self] call, result in
|
||||
guard call.method == WirelessDataPrompt.awaitDecisionMethod else {
|
||||
result(FlutterMethodNotImplemented)
|
||||
return
|
||||
}
|
||||
guard let self else {
|
||||
result(nil)
|
||||
return
|
||||
}
|
||||
self.wirelessDataPrompt.awaitDecision(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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/>
|
||||
@@ -87,6 +87,10 @@
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>UIBackgroundModes</key>
|
||||
<array>
|
||||
<string>audio</string>
|
||||
</array>
|
||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||
<true/>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import Flutter
|
||||
import UIKit
|
||||
|
||||
class SceneDelegate: FlutterSceneDelegate {
|
||||
|
||||
override func sceneDidBecomeActive(_ scene: UIScene) {
|
||||
super.sceneDidBecomeActive(scene)
|
||||
(UIApplication.shared.delegate as? AppDelegate)?.requestWirelessDataPrompt()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import CoreTelephony
|
||||
import Flutter
|
||||
import Foundation
|
||||
|
||||
/// 监听系统无线数据选择,并用 URLSession 唤起系统选择框。
|
||||
final class WirelessDataPrompt {
|
||||
static let channelName = "com.stormg.lumadrama/wireless-data"
|
||||
static let awaitDecisionMethod = "awaitDecision"
|
||||
|
||||
/// 系统选择框由 URLSession 触发,Dart 的 Socket 请求不会弹出。
|
||||
private static let promptURL = URL(string: "https://captive.apple.com/hotspot-detect.html")
|
||||
|
||||
private let cellularData = CTCellularData()
|
||||
private let lock = NSLock()
|
||||
private var pending: [FlutterResult] = []
|
||||
private var decided = false
|
||||
private var didRequestPrompt = false
|
||||
|
||||
init() {
|
||||
cellularData.cellularDataRestrictionDidUpdateNotifier = { [weak self] state in
|
||||
DispatchQueue.main.async {
|
||||
self?.completeIfDecided(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 应用进入前台后请求一次,促使系统弹出无线数据选择。
|
||||
func requestSystemPrompt() {
|
||||
guard !didRequestPrompt, let promptURL = Self.promptURL else {
|
||||
return
|
||||
}
|
||||
didRequestPrompt = true
|
||||
_ = cellularData.restrictedState
|
||||
URLSession.shared.dataTask(with: promptURL) { _, _, _ in }.resume()
|
||||
}
|
||||
|
||||
/// 未允许前先挂起;用户允许无线数据后再放行。
|
||||
func awaitDecision(_ result: @escaping FlutterResult) {
|
||||
lock.lock()
|
||||
if decided {
|
||||
lock.unlock()
|
||||
DispatchQueue.main.async {
|
||||
result(nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
pending.append(result)
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
private func completeIfDecided(_ state: CTCellularDataRestrictedState) {
|
||||
if state != .notRestricted {
|
||||
return
|
||||
}
|
||||
lock.lock()
|
||||
if decided {
|
||||
lock.unlock()
|
||||
return
|
||||
}
|
||||
decided = true
|
||||
let waiters = pending
|
||||
pending.removeAll()
|
||||
lock.unlock()
|
||||
waiters.forEach { $0(nil) }
|
||||
}
|
||||
}
|
||||
+41
-15
@@ -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';
|
||||
@@ -30,6 +31,7 @@ import 'core/data/repositories/favorite_repository.dart';
|
||||
import 'core/data/repositories/interaction_repository.dart';
|
||||
import 'core/data/repositories/notice_repository.dart';
|
||||
import 'core/data/repositories/playback_repository.dart';
|
||||
import 'core/data/repositories/playlist_repository.dart';
|
||||
import 'core/data/repositories/search_repository.dart';
|
||||
import 'core/data/repositories/store_repository.dart';
|
||||
import 'core/data/repositories/watch_history_repository.dart';
|
||||
@@ -41,6 +43,7 @@ import 'core/data/services/download_controller.dart';
|
||||
import 'core/data/services/favorite_controller.dart';
|
||||
import 'core/data/services/interaction_controller.dart';
|
||||
import 'core/data/services/locale_controller.dart';
|
||||
import 'core/data/services/playlist_controller.dart';
|
||||
import 'core/data/services/event_tracker.dart';
|
||||
import 'core/data/services/playback_position_cache.dart';
|
||||
import 'core/data/services/playback_session.dart';
|
||||
@@ -83,6 +86,7 @@ class LumaDramaApp extends StatefulWidget {
|
||||
this.commerceRepository,
|
||||
this.storeRepository,
|
||||
this.searchRepository,
|
||||
this.playlistRepository,
|
||||
this.haptics = const FlutterHaptics(),
|
||||
});
|
||||
|
||||
@@ -103,6 +107,7 @@ class LumaDramaApp extends StatefulWidget {
|
||||
final CommerceRepository? commerceRepository;
|
||||
final StoreRepository? storeRepository;
|
||||
final SearchRepository? searchRepository;
|
||||
final PlaylistRepository? playlistRepository;
|
||||
final Haptics haptics;
|
||||
|
||||
@override
|
||||
@@ -113,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(
|
||||
@@ -126,8 +132,10 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
_sessionStore,
|
||||
);
|
||||
|
||||
late final CatalogApi _catalogApi = CatalogApi(_apiClient);
|
||||
|
||||
late final CatalogRepository _catalogRepository =
|
||||
widget.catalogRepository ?? HttpCatalogRepository(CatalogApi(_apiClient));
|
||||
widget.catalogRepository ?? HttpCatalogRepository(_catalogApi);
|
||||
|
||||
late final CategoryRepository _categoryRepository =
|
||||
widget.categoryRepository ??
|
||||
@@ -135,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 ??
|
||||
@@ -177,6 +179,13 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
late final SearchRepository _searchRepository =
|
||||
widget.searchRepository ?? HttpSearchRepository(CatalogApi(_apiClient));
|
||||
|
||||
/// 测试注入了目录仓库时不打剧单接口,剧单页继续用本地分区。
|
||||
late final PlaylistRepository? _playlistRepository =
|
||||
widget.playlistRepository ??
|
||||
(widget.catalogRepository == null
|
||||
? HttpPlaylistRepository(CatalogApi(_apiClient))
|
||||
: null);
|
||||
|
||||
late final StoreRepository _storeRepository =
|
||||
widget.storeRepository ?? HttpStoreRepository(CommerceApi(_apiClient));
|
||||
|
||||
@@ -206,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());
|
||||
}
|
||||
@@ -222,6 +231,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
unawaited(_walletController.load());
|
||||
} else {
|
||||
_favoriteController.clear();
|
||||
unawaited(_favoriteController.load());
|
||||
_downloadController.reset();
|
||||
_walletController.reset();
|
||||
}
|
||||
@@ -239,14 +249,26 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
CategoryController _createCategories() {
|
||||
final controller = CategoryController(_categoryRepository);
|
||||
if (widget.catalogRepository == null) {
|
||||
controller.dramaPageLoader = CategoryApi(_apiClient).dramas;
|
||||
}
|
||||
controller.load();
|
||||
return controller;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final playlists = _playlistRepository;
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
Provider(create: (_) => PlaybackCoordinator()),
|
||||
Provider<EventTracker>(create: (_) => EventTracker(_apiClient)),
|
||||
Provider<PlayerFactory>(create: (_) => widget.playerFactory),
|
||||
Provider<CatalogRepository>.value(value: _catalogRepository),
|
||||
if (widget.catalogRepository == null)
|
||||
Provider<CatalogApi>.value(value: _catalogApi),
|
||||
Provider<PlaybackRepository>.value(value: _playback),
|
||||
Provider<PlaybackPositionCache>.value(value: _playbackPositionCache),
|
||||
Provider<WatchHistoryRepository>.value(value: _watchHistory),
|
||||
@@ -260,11 +282,15 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
Provider<SearchRepository>.value(value: _searchRepository),
|
||||
Provider<Haptics>.value(value: widget.haptics),
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => CatalogController(_catalogRepository)..load(),
|
||||
),
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => CategoryController(_categoryRepository)..load(),
|
||||
create: (_) {
|
||||
final catalog = CatalogController(_catalogRepository);
|
||||
if (widget.catalogRepository != null) catalog.load();
|
||||
return catalog;
|
||||
},
|
||||
),
|
||||
ChangeNotifierProvider(create: (_) => _createCategories()),
|
||||
if (playlists != null)
|
||||
ChangeNotifierProvider(create: (_) => PlaylistController(playlists)),
|
||||
ChangeNotifierProvider.value(value: _favoriteController),
|
||||
ChangeNotifierProvider.value(value: _downloadController),
|
||||
ChangeNotifierProvider.value(value: _walletController),
|
||||
|
||||
@@ -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 直连本机服务;不可达时回落到公网地址。
|
||||
@@ -51,9 +51,12 @@ class AppConfig {
|
||||
? _runtimeBaseUrl
|
||||
: (compiledBaseUrl.isNotEmpty ? compiledBaseUrl : defaultBaseUrl);
|
||||
|
||||
static final String _defaultBaseUrl = _runsOnDevMachine
|
||||
? lanBaseUrl
|
||||
: devHostBaseUrl;
|
||||
/// 生产包固定走公网地址;仅 debug 才按平台默认到环回/开发机。
|
||||
static final String _defaultBaseUrl = kReleaseMode
|
||||
? publicBaseUrl
|
||||
: (_runsOnDevMachine
|
||||
? lanBaseUrl
|
||||
: devHostBaseUrl);
|
||||
|
||||
/// 模拟器、桌面端与开发机同机,环回地址可用;iOS 真机不满足。
|
||||
/// Android 没有等价的探测方式,统一按真机处理(模拟器用
|
||||
@@ -93,6 +96,11 @@ class AppConfig {
|
||||
if (_runtimeBaseUrl.isEmpty) applyRuntimeBaseUrl(compiled);
|
||||
return;
|
||||
}
|
||||
// 生产包固定公网地址,不再探测环回/开发机局域网地址,避免请求到开发机。
|
||||
if (kReleaseMode) {
|
||||
if (_runtimeBaseUrl.isEmpty) applyRuntimeBaseUrl(publicBaseUrl);
|
||||
return;
|
||||
}
|
||||
final candidates = <String>[
|
||||
if (_runtimeBaseUrl.isNotEmpty) _runtimeBaseUrl,
|
||||
for (final candidate in _probeCandidates)
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// 服务端内容分类。id 按契约保持字符串,避免雪花 ID 精度丢失。
|
||||
class ContentCategory {
|
||||
const ContentCategory({required this.id, required this.name});
|
||||
const ContentCategory({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.locales = const {},
|
||||
});
|
||||
|
||||
final String id;
|
||||
|
||||
/// 中文名称,与 locales 里的 zh 相同。
|
||||
final String name;
|
||||
final Map<String, String> locales;
|
||||
|
||||
/// 解析 `GET /app/categories` 的单项。
|
||||
factory ContentCategory.fromJson(Map<String, dynamic> json) {
|
||||
return ContentCategory(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
name: json['name'] as String? ?? '',
|
||||
);
|
||||
final locales = localeMap(json['locales']);
|
||||
final name = json['name'] as String? ?? locales['zh'] ?? '';
|
||||
return ContentCategory(id: (json['id'] ?? '').toString(), name: name, locales: locales);
|
||||
}
|
||||
|
||||
/// 按界面语言取名称。缺对应语言时回落到中文。
|
||||
String localizedName(String languageCode) {
|
||||
return localizedText(languageCode, name, locales);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'json_numbers.dart';
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// 短剧与剧集,字段与后端 `/app/**` 的下发结构对应。
|
||||
///
|
||||
@@ -18,6 +21,7 @@ class Episode {
|
||||
this.likeCount,
|
||||
this.commentCount,
|
||||
this.thumbnailsUrl,
|
||||
this.posterUrl,
|
||||
});
|
||||
|
||||
final String id;
|
||||
@@ -34,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,
|
||||
@@ -51,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) {
|
||||
@@ -65,6 +86,7 @@ class Episode {
|
||||
likeCount: _optionalInt(json['likeCount']),
|
||||
commentCount: _optionalInt(json['commentCount']),
|
||||
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
|
||||
posterUrl: _optionalString(json['posterUrl']),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -76,7 +98,14 @@ class Drama {
|
||||
required this.synopsis,
|
||||
required this.posterUrl,
|
||||
this.episodes = const [],
|
||||
this.titleLocales = const {},
|
||||
this.synopsisLocales = const {},
|
||||
this.tag = '',
|
||||
this.tagLocales = const {},
|
||||
this.tagColor = '',
|
||||
this.category = '',
|
||||
this.categoryLocales = const {},
|
||||
this.types = const [],
|
||||
this.genre = '',
|
||||
this.totalEpisodes = 0,
|
||||
this.freeEpisodes = 0,
|
||||
@@ -94,9 +123,16 @@ class Drama {
|
||||
final String id;
|
||||
final String title;
|
||||
final String synopsis;
|
||||
final Map<String, String> titleLocales;
|
||||
final Map<String, String> synopsisLocales;
|
||||
final String tag;
|
||||
final Map<String, String> tagLocales;
|
||||
final String tagColor;
|
||||
final String posterUrl;
|
||||
final List<Episode> episodes;
|
||||
final String category;
|
||||
final Map<String, String> categoryLocales;
|
||||
final List<Map<String, String>> types;
|
||||
final String genre;
|
||||
final int totalEpisodes;
|
||||
final int freeEpisodes;
|
||||
@@ -127,19 +163,26 @@ class Drama {
|
||||
/// 列表卡片:带一集可播预览(首页直接起播),完整剧集进详情再取。
|
||||
factory Drama.fromCardJson(Map<String, dynamic> json) {
|
||||
final preview = json['preview'];
|
||||
final text = _DramaText.fromJson(json);
|
||||
return Drama(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
title: json['title'] as String? ?? '',
|
||||
synopsis: json['synopsis'] as String? ?? '',
|
||||
title: text.title,
|
||||
synopsis: text.synopsis,
|
||||
titleLocales: text.titleLocales,
|
||||
synopsisLocales: text.synopsisLocales,
|
||||
tag: text.tag,
|
||||
tagLocales: text.tagLocales,
|
||||
tagColor: json['tagColor'] as String? ?? '',
|
||||
posterUrl: json['cover'] as String? ?? '',
|
||||
episodes: preview is Map<String, dynamic>
|
||||
? [Episode.fromJson(preview)]
|
||||
: const [],
|
||||
category: json['category'] as String? ?? '',
|
||||
genre: json['genre'] as String? ?? '',
|
||||
category: text.category,
|
||||
categoryLocales: text.categoryLocales,
|
||||
types: text.types,
|
||||
genre: text.genre,
|
||||
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
||||
isHot: json['isHot'] == true,
|
||||
// viewCount 后端是 Long,按字符串下发(见 json_numbers.dart)
|
||||
viewCount: jsonToInt(json['viewCount']),
|
||||
likeCount: _optionalInt(json['likeCount']),
|
||||
favoriteCount: _optionalInt(json['favoriteCount']),
|
||||
@@ -152,13 +195,21 @@ class Drama {
|
||||
|
||||
/// 详情:带剧集列表。
|
||||
factory Drama.fromDetailJson(Map<String, dynamic> json) {
|
||||
final text = _DramaText.fromJson(json);
|
||||
return Drama(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
title: json['title'] as String? ?? '',
|
||||
synopsis: json['synopsis'] as String? ?? '',
|
||||
title: text.title,
|
||||
synopsis: text.synopsis,
|
||||
titleLocales: text.titleLocales,
|
||||
synopsisLocales: text.synopsisLocales,
|
||||
tag: text.tag,
|
||||
tagLocales: text.tagLocales,
|
||||
tagColor: json['tagColor'] as String? ?? '',
|
||||
posterUrl: json['cover'] as String? ?? '',
|
||||
category: json['category'] as String? ?? '',
|
||||
genre: json['genre'] as String? ?? '',
|
||||
category: text.category,
|
||||
categoryLocales: text.categoryLocales,
|
||||
types: text.types,
|
||||
genre: text.genre,
|
||||
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
||||
freeEpisodes: (json['freeEpisodes'] as num?)?.toInt() ?? 0,
|
||||
isHot: json['isHot'] == true,
|
||||
@@ -176,6 +227,37 @@ class Drama {
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
String localizedTitle(String languageCode) {
|
||||
return localizedText(languageCode, title, titleLocales);
|
||||
}
|
||||
|
||||
String localizedSynopsis(String languageCode) {
|
||||
return localizedText(languageCode, synopsis, synopsisLocales);
|
||||
}
|
||||
|
||||
String localizedTag(String languageCode) {
|
||||
return localizedText(languageCode, tag, tagLocales);
|
||||
}
|
||||
|
||||
/// 标签角标背景色。接口没给合法色值时用 fallback。
|
||||
Color tagRibbonColor(Color fallback) {
|
||||
final parsed = _colorFromHex(tagColor);
|
||||
return parsed ?? fallback;
|
||||
}
|
||||
|
||||
/// 按当前语言取类型名称。接口没带语言表时返回空,调用方继续用中文 genre。
|
||||
List<String> localizedTypeLabels(String languageCode) {
|
||||
final labels = <String>[];
|
||||
for (final item in types) {
|
||||
final label = localizedText(languageCode, item['zh'] ?? '', item);
|
||||
if (label.isNotEmpty && !labels.contains(label)) labels.add(label);
|
||||
}
|
||||
if (labels.isNotEmpty) return labels;
|
||||
final primary = localizedText(languageCode, '', categoryLocales);
|
||||
if (primary.isNotEmpty) return [primary];
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
int? _optionalInt(dynamic value) => value == null ? null : jsonToInt(value);
|
||||
@@ -184,3 +266,81 @@ String? _optionalString(dynamic value) {
|
||||
final text = value is String ? value.trim() : '';
|
||||
return text.isEmpty ? null : text;
|
||||
}
|
||||
|
||||
Color? _colorFromHex(String raw) {
|
||||
final text = raw.trim();
|
||||
if (text.length != 7 || !text.startsWith('#')) return null;
|
||||
final value = int.tryParse(text.substring(1), radix: 16);
|
||||
if (value == null) return null;
|
||||
return Color(0xFF000000 | value);
|
||||
}
|
||||
|
||||
List<Map<String, String>> _typeLocales(Object? raw) {
|
||||
if (raw is! List) return const [];
|
||||
return raw.whereType<Map>().map(localeMap).toList(growable: false);
|
||||
}
|
||||
|
||||
/// 从语言表还原中文展示字段。列表接口不再单独下发 title / synopsis / tag。
|
||||
class _DramaText {
|
||||
const _DramaText({
|
||||
required this.title,
|
||||
required this.synopsis,
|
||||
required this.titleLocales,
|
||||
required this.synopsisLocales,
|
||||
required this.tag,
|
||||
required this.tagLocales,
|
||||
required this.category,
|
||||
required this.categoryLocales,
|
||||
required this.types,
|
||||
required this.genre,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String synopsis;
|
||||
final Map<String, String> titleLocales;
|
||||
final Map<String, String> synopsisLocales;
|
||||
final String tag;
|
||||
final Map<String, String> tagLocales;
|
||||
final String category;
|
||||
final Map<String, String> categoryLocales;
|
||||
final List<Map<String, String>> types;
|
||||
final String genre;
|
||||
|
||||
factory _DramaText.fromJson(Map<String, dynamic> json) {
|
||||
final titleLocales = localeMap(json['titleLocales']);
|
||||
final synopsisLocales = localeMap(json['synopsisLocales']);
|
||||
final tagLocales = localeMap(json['tagLocales']);
|
||||
final categoryLocales = localeMap(json['categoryLocales']);
|
||||
final types = _typeLocales(json['types']);
|
||||
final category = _firstText(categoryLocales, json['category'], types);
|
||||
return _DramaText(
|
||||
title: _firstText(titleLocales, json['title']),
|
||||
synopsis: _firstText(synopsisLocales, json['synopsis'] ?? json['description']),
|
||||
titleLocales: titleLocales,
|
||||
synopsisLocales: synopsisLocales,
|
||||
tag: _firstText(tagLocales, json['tag']),
|
||||
tagLocales: tagLocales,
|
||||
category: category,
|
||||
categoryLocales: categoryLocales,
|
||||
types: types,
|
||||
genre: _genreText(types, json['genre']),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _firstText(Map<String, String> locales, Object? fallback, [List<Map<String, String>>? types]) {
|
||||
final chinese = locales['zh'] ?? '';
|
||||
if (chinese.isNotEmpty) return chinese;
|
||||
if (types != null && types.isNotEmpty) {
|
||||
final label = types.first['zh'] ?? '';
|
||||
if (label.isNotEmpty) return label;
|
||||
}
|
||||
return fallback is String ? fallback : '';
|
||||
}
|
||||
|
||||
String _genreText(List<Map<String, String>> types, Object? fallback) {
|
||||
final names = types.map((item) => item['zh'] ?? '').where((value) => value.isNotEmpty);
|
||||
final joined = names.join(' / ');
|
||||
if (joined.isNotEmpty) return joined;
|
||||
return fallback is String ? fallback : '';
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ class FeedSection {
|
||||
factory FeedSection.fromJson(Map<String, dynamic> json) {
|
||||
return FeedSection(
|
||||
code: json['code'] as String? ?? '',
|
||||
title: json['title'] as String? ?? '',
|
||||
title: _sectionTitle(json),
|
||||
dramas: (json['dramas'] as List? ?? const [])
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(Drama.fromCardJson)
|
||||
@@ -84,3 +84,12 @@ class FeedBanner {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _sectionTitle(Map<String, dynamic> json) {
|
||||
final locales = json['titleLocales'];
|
||||
if (locales is Map) {
|
||||
final chinese = locales['zh']?.toString() ?? '';
|
||||
if (chinese.isNotEmpty) return chinese;
|
||||
}
|
||||
return json['title'] as String? ?? '';
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
/// 把接口里的语言表解析成字符串映射。
|
||||
Map<String, String> localeMap(Object? raw) {
|
||||
if (raw is! Map) return const {};
|
||||
return raw.map((key, value) => MapEntry('$key', value?.toString() ?? ''));
|
||||
}
|
||||
|
||||
/// 按当前语言取文案。没有对应语言时用中文,中文也没有时用 fallback。
|
||||
String localizedText(String languageCode, String fallback, Map<String, String> locales) {
|
||||
final selected = locales[languageCode] ?? '';
|
||||
if (selected.isNotEmpty) return selected;
|
||||
final chinese = locales['zh'] ?? '';
|
||||
if (chinese.isNotEmpty) return chinese;
|
||||
return fallback;
|
||||
}
|
||||
@@ -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']),
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'drama.dart';
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// C 端剧单:`GET /app/playlists` 与 `GET /app/playlists/{id}` 的同一结构。
|
||||
class PlaylistDetail {
|
||||
const PlaylistDetail({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.description,
|
||||
this.locales = const {},
|
||||
this.descriptionLocales = const {},
|
||||
required this.dramaCount,
|
||||
required this.dramas,
|
||||
this.pageIndex = 1,
|
||||
this.pageSize = 0,
|
||||
});
|
||||
|
||||
final String id;
|
||||
|
||||
/// 中文名称,与 locales 里的 zh 相同。
|
||||
final String name;
|
||||
final Map<String, String> locales;
|
||||
|
||||
/// 中文描述,与 descriptionLocales 里的 zh 相同。
|
||||
final String description;
|
||||
final Map<String, String> descriptionLocales;
|
||||
final int dramaCount;
|
||||
final int pageIndex;
|
||||
final int pageSize;
|
||||
final List<Drama> dramas;
|
||||
|
||||
factory PlaylistDetail.fromJson(Map<String, dynamic> json) {
|
||||
final dramas = _dramasOf(json['list']);
|
||||
final locales = localeMap(json['locales']);
|
||||
final descriptions = localeMap(json['descriptionLocales']);
|
||||
return PlaylistDetail(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
name: json['name'] as String? ?? locales['zh'] ?? '',
|
||||
locales: locales,
|
||||
description: json['description'] as String? ?? descriptions['zh'] ?? '',
|
||||
descriptionLocales: descriptions,
|
||||
dramaCount: (json['dramaCount'] as num?)?.toInt() ?? dramas.length,
|
||||
pageIndex: (json['pageIndex'] as num?)?.toInt() ?? 1,
|
||||
pageSize: (json['pageSize'] as num?)?.toInt() ?? dramas.length,
|
||||
dramas: dramas,
|
||||
);
|
||||
}
|
||||
|
||||
/// 按界面语言取名称。缺对应语言时回落到中文。
|
||||
String localizedName(String languageCode) {
|
||||
return localizedText(languageCode, name, locales);
|
||||
}
|
||||
|
||||
/// 按界面语言取描述。缺对应语言时回落到中文。
|
||||
String localizedDescription(String languageCode) {
|
||||
return localizedText(languageCode, description, descriptionLocales);
|
||||
}
|
||||
}
|
||||
|
||||
List<Drama> _dramasOf(Object? rows) {
|
||||
if (rows is! List) return const [];
|
||||
return rows
|
||||
.whereType<Map>()
|
||||
.map((item) => Drama.fromCardJson(Map<String, dynamic>.from(item)))
|
||||
.toList(growable: false);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'json_numbers.dart';
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// 服务端续看记录:`GET /app/watch/progress?dramaId=` 与 `/app/watch/recent` 的下发结构。
|
||||
///
|
||||
@@ -13,6 +14,7 @@ class WatchProgress {
|
||||
required this.position,
|
||||
required this.duration,
|
||||
this.dramaTitle,
|
||||
this.titleLocales = const {},
|
||||
this.dramaCover,
|
||||
this.episodeNumber,
|
||||
this.totalEpisodes,
|
||||
@@ -25,6 +27,7 @@ class WatchProgress {
|
||||
final String dramaId;
|
||||
final String episodeId;
|
||||
final String? dramaTitle;
|
||||
final Map<String, String> titleLocales;
|
||||
final String? dramaCover;
|
||||
final int? episodeNumber;
|
||||
final int? totalEpisodes;
|
||||
@@ -45,11 +48,17 @@ class WatchProgress {
|
||||
return (position.inMilliseconds / duration.inMilliseconds).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
/// 按当前语言取剧名。没有对应语言时回退中文,再回退 dramaTitle。
|
||||
String localizedTitle(String languageCode) {
|
||||
return localizedText(languageCode, dramaTitle ?? '', titleLocales);
|
||||
}
|
||||
|
||||
factory WatchProgress.fromJson(Map<String, dynamic> json) {
|
||||
return WatchProgress(
|
||||
dramaId: (json['dramaId'] ?? '').toString(),
|
||||
episodeId: (json['episodeId'] ?? '').toString(),
|
||||
dramaTitle: json['dramaTitle']?.toString(),
|
||||
titleLocales: localeMap(json['titleLocales']),
|
||||
dramaCover: json['dramaCover']?.toString(),
|
||||
episodeNumber: json['episodeNumber'] == null
|
||||
? null
|
||||
@@ -72,6 +81,7 @@ class WatchProgress {
|
||||
'dramaId': dramaId,
|
||||
'episodeId': episodeId,
|
||||
if (dramaTitle != null) 'dramaTitle': dramaTitle,
|
||||
if (titleLocales.isNotEmpty) 'titleLocales': titleLocales,
|
||||
if (dramaCover != null) 'dramaCover': dramaCover,
|
||||
if (episodeNumber != null) 'episodeNumber': episodeNumber,
|
||||
if (totalEpisodes != null) 'totalEpisodes': totalEpisodes,
|
||||
|
||||
@@ -31,9 +31,13 @@ class WatchRecord {
|
||||
}
|
||||
|
||||
/// 服务端分页标题优先,详情标题作为回退。
|
||||
String get displayTitle {
|
||||
final pageTitle = progress.dramaTitle?.trim() ?? '';
|
||||
return pageTitle.isNotEmpty ? pageTitle : drama?.title.trim() ?? '';
|
||||
String get displayTitle => localizedDisplayTitle('zh');
|
||||
|
||||
/// 按当前语言取标题。分页语言表优先,详情语言表作为回退。
|
||||
String localizedDisplayTitle(String languageCode) {
|
||||
final pageTitle = progress.localizedTitle(languageCode).trim();
|
||||
if (pageTitle.isNotEmpty) return pageTitle;
|
||||
return drama?.localizedTitle(languageCode).trim() ?? '';
|
||||
}
|
||||
|
||||
/// 服务端分页封面优先,详情封面作为回退。
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import '../models/content_category.dart';
|
||||
import '../models/drama.dart';
|
||||
import '../models/feed_page.dart';
|
||||
import '../models/home_feed.dart';
|
||||
import '../models/page_result.dart';
|
||||
import '../models/playlist_detail.dart';
|
||||
import '../models/search_result.dart';
|
||||
import 'api_client.dart';
|
||||
|
||||
@@ -58,12 +61,95 @@ class CatalogApi {
|
||||
return SearchResult.fromJson(_asMap(data));
|
||||
}
|
||||
|
||||
static const int playlistPageSize = 10;
|
||||
static const int playlistDramaPageSize = 20;
|
||||
|
||||
/// 已启用剧单,分页返回,每条带已上线短剧卡片。
|
||||
Future<PageResult<PlaylistDetail>> playlists({
|
||||
int pageIndex = 1,
|
||||
int pageSize = playlistPageSize,
|
||||
}) async {
|
||||
final data = await _client.get(
|
||||
'/app/playlists',
|
||||
query: {
|
||||
'pageIndex': '$pageIndex',
|
||||
'pageSize': '$pageSize',
|
||||
},
|
||||
);
|
||||
return PageResult.parse(data, PlaylistDetail.fromJson);
|
||||
}
|
||||
|
||||
/// 单个剧单详情。短剧按 pageIndex、pageSize 翻页。
|
||||
Future<PlaylistDetail> playlist(
|
||||
String id, {
|
||||
int pageIndex = 1,
|
||||
int pageSize = playlistDramaPageSize,
|
||||
}) async {
|
||||
return PlaylistDetail.fromJson(
|
||||
_asMap(
|
||||
await _client.get(
|
||||
'/app/playlists/$id',
|
||||
query: {
|
||||
'pageIndex': '$pageIndex',
|
||||
'pageSize': '$pageSize',
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 已启用首页分类,名称在 locales。
|
||||
Future<List<ContentCategory>> classifications() async {
|
||||
return _categories(await _client.get('/app/categories'));
|
||||
}
|
||||
|
||||
/// 已启用类型,名称在 locales。
|
||||
Future<List<ContentCategory>> dramaCategories() async {
|
||||
return _categories(await _client.get('/app/drama-categories'));
|
||||
}
|
||||
|
||||
/// 已启用标签,名称在 locales。
|
||||
Future<List<ContentCategory>> tags() async {
|
||||
return _categories(await _client.get('/app/tags'));
|
||||
}
|
||||
|
||||
static const int libraryPageSize = 20;
|
||||
|
||||
/// 全部短剧。同一组 id 多选为或,组与组之间为且。
|
||||
Future<PageResult<Drama>> libraryDramas({
|
||||
List<String> categoryIds = const [],
|
||||
List<String> classificationIds = const [],
|
||||
List<String> tagIds = const [],
|
||||
int pageIndex = 1,
|
||||
int pageSize = libraryPageSize,
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
'/app/dramas/page',
|
||||
body: {
|
||||
'pageIndex': pageIndex,
|
||||
'pageSize': pageSize,
|
||||
'categoryIds': categoryIds,
|
||||
'classificationIds': classificationIds,
|
||||
'tagIds': tagIds,
|
||||
},
|
||||
);
|
||||
return PageResult.parse(data, Drama.fromCardJson);
|
||||
}
|
||||
|
||||
Future<Drama> dramaDetail(String dramaId) async {
|
||||
return Drama.fromDetailJson(
|
||||
_asMap(await _client.get('/app/dramas/$dramaId')),
|
||||
);
|
||||
}
|
||||
|
||||
List<ContentCategory> _categories(Object? data) {
|
||||
if (data is! List) return const [];
|
||||
return [
|
||||
for (final item in data)
|
||||
if (item is Map<String, dynamic>) ContentCategory.fromJson(item),
|
||||
];
|
||||
}
|
||||
|
||||
Map<String, dynamic> _asMap(Object? data) {
|
||||
if (data is Map<String, dynamic>) return data;
|
||||
throw const ApiException(-1, '返回数据格式异常');
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import '../models/content_category.dart';
|
||||
import '../models/drama.dart';
|
||||
import '../models/page_result.dart';
|
||||
import 'api_client.dart';
|
||||
|
||||
/// 内容分类接口,对应契约 `GET /app/categories`。
|
||||
class CategoryApi {
|
||||
const CategoryApi(this._client);
|
||||
|
||||
static const int dramaPageSize = 20;
|
||||
|
||||
final ApiClient _client;
|
||||
|
||||
/// 拉取已启用分类,id 全程按字符串解析。
|
||||
@@ -18,4 +22,20 @@ class CategoryApi {
|
||||
if (item is Map<String, dynamic>) ContentCategory.fromJson(item),
|
||||
];
|
||||
}
|
||||
|
||||
/// 分类下已上线短剧,pageIndex 从 1 开始。
|
||||
Future<PageResult<Drama>> dramas(
|
||||
String categoryId, {
|
||||
int pageIndex = 1,
|
||||
int pageSize = dramaPageSize,
|
||||
}) async {
|
||||
final data = await _client.get(
|
||||
'/app/categories/$categoryId/dramas',
|
||||
query: {
|
||||
'pageIndex': '$pageIndex',
|
||||
'pageSize': '$pageSize',
|
||||
},
|
||||
);
|
||||
return PageResult.parse(data, Drama.fromCardJson);
|
||||
}
|
||||
}
|
||||
@@ -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 '';
|
||||
}
|
||||
@@ -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, '返回数据格式异常');
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import '../models/page_result.dart';
|
||||
import '../models/playlist_detail.dart';
|
||||
import '../remote/catalog_api.dart';
|
||||
|
||||
/// 剧单来源:列表分页拉取,详情用于打开单条时刷新。
|
||||
abstract interface class PlaylistRepository {
|
||||
Future<PageResult<PlaylistDetail>> fetchPlaylists({
|
||||
int pageIndex = 1,
|
||||
int pageSize = CatalogApi.playlistPageSize,
|
||||
});
|
||||
|
||||
Future<PlaylistDetail> fetchPlaylist(
|
||||
String id, {
|
||||
int pageIndex = 1,
|
||||
int pageSize = CatalogApi.playlistDramaPageSize,
|
||||
});
|
||||
}
|
||||
|
||||
class HttpPlaylistRepository implements PlaylistRepository {
|
||||
HttpPlaylistRepository(this._api);
|
||||
|
||||
final CatalogApi _api;
|
||||
|
||||
@override
|
||||
Future<PageResult<PlaylistDetail>> fetchPlaylists({
|
||||
int pageIndex = 1,
|
||||
int pageSize = CatalogApi.playlistPageSize,
|
||||
}) => _api.playlists(pageIndex: pageIndex, pageSize: pageSize);
|
||||
|
||||
@override
|
||||
Future<PlaylistDetail> fetchPlaylist(
|
||||
String id, {
|
||||
int pageIndex = 1,
|
||||
int pageSize = CatalogApi.playlistDramaPageSize,
|
||||
}) => _api.playlist(id, pageIndex: pageIndex, pageSize: pageSize);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
// Author: fruit.com.cn
|
||||
// 全部短剧筛选与分页:拉取分类、类型、标签,并按页加载短剧。
|
||||
|
||||
import '../models/content_category.dart';
|
||||
import '../models/drama.dart';
|
||||
import '../models/page_result.dart';
|
||||
import '../remote/catalog_api.dart';
|
||||
|
||||
/// 全部短剧筛选与分页所需的远端能力。
|
||||
abstract interface class AllDramasRemote {
|
||||
/// 已启用分类。
|
||||
Future<List<ContentCategory>> classifications();
|
||||
|
||||
/// 已启用类型。
|
||||
Future<List<ContentCategory>> categories();
|
||||
|
||||
/// 已启用标签。
|
||||
Future<List<ContentCategory>> tags();
|
||||
|
||||
/// 按当前筛选取一页短剧。
|
||||
Future<PageResult<Drama>> dramas({
|
||||
required List<String> categoryIds,
|
||||
required List<String> classificationIds,
|
||||
required List<String> tagIds,
|
||||
required int pageIndex,
|
||||
});
|
||||
}
|
||||
|
||||
/// 用现有目录接口实现全部短剧远端能力。
|
||||
class CatalogAllDramasRemote implements AllDramasRemote {
|
||||
/// 绑定目录接口。
|
||||
const CatalogAllDramasRemote(this._api);
|
||||
|
||||
final CatalogApi _api;
|
||||
|
||||
@override
|
||||
Future<List<ContentCategory>> classifications() => _api.classifications();
|
||||
|
||||
@override
|
||||
Future<List<ContentCategory>> categories() => _api.dramaCategories();
|
||||
|
||||
@override
|
||||
Future<List<ContentCategory>> tags() => _api.tags();
|
||||
|
||||
@override
|
||||
Future<PageResult<Drama>> dramas({
|
||||
required List<String> categoryIds,
|
||||
required List<String> classificationIds,
|
||||
required List<String> tagIds,
|
||||
required int pageIndex,
|
||||
}) {
|
||||
return _api.libraryDramas(
|
||||
categoryIds: categoryIds,
|
||||
classificationIds: classificationIds,
|
||||
tagIds: tagIds,
|
||||
pageIndex: pageIndex,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 全部短剧:筛选项来自类型、分类、标签,列表按页加载。
|
||||
class AllDramasController {
|
||||
AllDramasController({
|
||||
AllDramasRemote? api,
|
||||
this.classifications = const [],
|
||||
this.categories = const [],
|
||||
this.tags = const [],
|
||||
this.dramas = const [],
|
||||
}) : _api = api; // ignore: prefer_initializing_formals
|
||||
|
||||
final AllDramasRemote? _api;
|
||||
List<ContentCategory> classifications;
|
||||
List<ContentCategory> categories;
|
||||
List<ContentCategory> tags;
|
||||
final Set<String> selectedClassifications = {};
|
||||
final Set<String> selectedCategories = {};
|
||||
final Set<String> selectedTags = {};
|
||||
List<Drama> dramas;
|
||||
bool loading = false;
|
||||
bool loadingMore = false;
|
||||
bool hasMore = false;
|
||||
String? error;
|
||||
int _page = 1;
|
||||
int _total = 0;
|
||||
|
||||
bool get usesRemote => _api != null;
|
||||
|
||||
/// 预览用:筛选项和列表都已在本地,不请求接口。
|
||||
factory AllDramasController.preview({
|
||||
List<ContentCategory> classifications = const [],
|
||||
List<ContentCategory> categories = const [],
|
||||
List<ContentCategory> tags = const [],
|
||||
List<Drama> dramas = const [],
|
||||
}) {
|
||||
return AllDramasController(
|
||||
classifications: classifications,
|
||||
categories: categories,
|
||||
tags: tags,
|
||||
dramas: dramas,
|
||||
);
|
||||
}
|
||||
|
||||
/// 从第一页重新拉取筛选项和短剧。没有接口时直接返回。
|
||||
Future<void> refresh() async {
|
||||
if (_api == null) return;
|
||||
loading = true;
|
||||
error = null;
|
||||
_page = 1;
|
||||
try {
|
||||
final filters = await Future.wait([
|
||||
_api.classifications(),
|
||||
_api.categories(),
|
||||
_api.tags(),
|
||||
]);
|
||||
classifications = filters[0];
|
||||
categories = filters[1];
|
||||
tags = filters[2];
|
||||
final page = await _loadPage(1);
|
||||
dramas = page;
|
||||
hasMore = dramas.length < _total;
|
||||
} catch (caught) {
|
||||
error = '$caught';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 追加下一页。没有更多、正在加载或没有接口时直接返回。
|
||||
Future<void> loadMore() async {
|
||||
if (_api == null || loading || loadingMore || !hasMore) return;
|
||||
loadingMore = true;
|
||||
error = null;
|
||||
try {
|
||||
final next = await _loadPage(_page + 1);
|
||||
_page += 1;
|
||||
dramas = [...dramas, ...next];
|
||||
hasMore = dramas.length < _total;
|
||||
} catch (caught) {
|
||||
error = '$caught';
|
||||
} finally {
|
||||
loadingMore = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 切换一个分类。传入空字符串表示清空这一组。
|
||||
void toggleClassification(String id) =>
|
||||
_toggle(selectedClassifications, id);
|
||||
|
||||
/// 切换一个类型。传入空字符串表示清空这一组。
|
||||
void toggleCategory(String id) => _toggle(selectedCategories, id);
|
||||
|
||||
/// 切换一个标签。传入空字符串表示清空这一组。
|
||||
void toggleTag(String id) => _toggle(selectedTags, id);
|
||||
|
||||
void _toggle(Set<String> selected, String id) {
|
||||
if (id.isEmpty) {
|
||||
selected.clear();
|
||||
return;
|
||||
}
|
||||
if (!selected.add(id)) selected.remove(id);
|
||||
}
|
||||
|
||||
Future<List<Drama>> _loadPage(int pageIndex) async {
|
||||
final page = await _api!.dramas(
|
||||
categoryIds: selectedCategories.toList(growable: false),
|
||||
classificationIds: selectedClassifications.toList(growable: false),
|
||||
tagIds: selectedTags.toList(growable: false),
|
||||
pageIndex: pageIndex,
|
||||
);
|
||||
_total = page.total;
|
||||
return page.list;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Native Android activity PiP; the Flutter playback session keeps the player.
|
||||
/// 原生活动级画中画桥:Android 是 Activity PiP(画面即 Flutter 渲染),
|
||||
/// iOS 是影子播放器接力(画面/声音来自原生 AVPlayer,退出时进度回传)。
|
||||
class AndroidPictureInPicture {
|
||||
AndroidPictureInPicture({MethodChannel? channel})
|
||||
: _channel = channel ?? const MethodChannel('com.stormg.lumadrama/pip');
|
||||
@@ -11,22 +12,147 @@ class AndroidPictureInPicture {
|
||||
final MethodChannel _channel;
|
||||
|
||||
bool get isPlatformSupported =>
|
||||
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
|
||||
!kIsWeb &&
|
||||
(defaultTargetPlatform == TargetPlatform.android ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS);
|
||||
|
||||
void setStateListener(ValueChanged<bool>? listener) {
|
||||
_channel.setMethodCallHandler(
|
||||
listener == null
|
||||
? null
|
||||
: (call) async {
|
||||
if (call.method == 'onPipChanged') {
|
||||
listener(call.arguments == true);
|
||||
}
|
||||
},
|
||||
);
|
||||
void Function(bool active, int finalPositionMs)? _pipChangedListener;
|
||||
VoidCallback? _playbackEndedListener;
|
||||
|
||||
/// PiP 状态回调:iOS 停止时 [finalPositionMs] 为影子最终进度(毫秒)。
|
||||
void setStateListener(void Function(bool active, int finalPositionMs)? listener) {
|
||||
_pipChangedListener = listener;
|
||||
_refreshHandler();
|
||||
}
|
||||
|
||||
Future<bool> enter() async {
|
||||
/// iOS 画中画内影子播完当前集(Android 不会触发)。
|
||||
void setPlaybackEndedListener(VoidCallback? listener) {
|
||||
_playbackEndedListener = listener;
|
||||
_refreshHandler();
|
||||
}
|
||||
|
||||
void _refreshHandler() {
|
||||
if (_pipChangedListener == null && _playbackEndedListener == null) {
|
||||
_channel.setMethodCallHandler(null);
|
||||
return;
|
||||
}
|
||||
_channel.setMethodCallHandler((call) async {
|
||||
switch (call.method) {
|
||||
case 'pipDebug':
|
||||
debugPrint('pip[native]: ${call.arguments}');
|
||||
case 'onPipChanged':
|
||||
final listener = _pipChangedListener;
|
||||
if (listener == null) return;
|
||||
final args = call.arguments;
|
||||
if (args is Map) {
|
||||
listener(
|
||||
args['active'] == true,
|
||||
(args['positionMs'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
} else {
|
||||
// Android 只回传 bool。
|
||||
listener(args == true, 0);
|
||||
}
|
||||
case 'onPipPlaybackEnded':
|
||||
_playbackEndedListener?.call();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 进入画中画。Android 忽略片源参数;iOS 用 [url] 与 [positionMs]
|
||||
/// 初始化影子播放器(对齐到当前进度、静音待命)。
|
||||
Future<bool> enter({required String url, required int positionMs}) async {
|
||||
if (!isPlatformSupported) return false;
|
||||
return await _channel.invokeMethod<bool>('enter') ?? false;
|
||||
return await _channel.invokeMethod<bool>('enter', {
|
||||
'url': url,
|
||||
'positionMs': positionMs,
|
||||
}) ??
|
||||
false;
|
||||
}
|
||||
|
||||
/// 创建影子播放器但不起播(仅 iOS):
|
||||
/// 自动小窗待命形态——静音暂停,退后台由 [armAutoEnter] 拉起。
|
||||
Future<void> prepareShadow({
|
||||
required String url,
|
||||
required int positionMs,
|
||||
bool autoEnter = false,
|
||||
}) async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('prepareShadow', {
|
||||
'url': url,
|
||||
'positionMs': positionMs,
|
||||
'autoEnter': autoEnter,
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 退后台瞬间把影子对齐到当前进度并静音起播,触发系统自动画中画(仅 iOS)。
|
||||
Future<void> armAutoEnter(int positionMs) async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('armAutoEnter', {
|
||||
'positionMs': positionMs,
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 回前台后影子回待命(暂停、静音)(仅 iOS)。
|
||||
Future<void> disarmAutoEnter() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('disarmAutoEnter');
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 显示原生还原过渡层(仅 iOS;还原动画开始时原生侧也会自动盖上)。
|
||||
Future<void> showRestoreOverlay() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('showRestoreOverlay');
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 淡出原生还原过渡层(仅 iOS;视频首帧确认后调用)。
|
||||
Future<void> hideRestoreOverlay() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('hideRestoreOverlay');
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 解除影子静音并起播(仅 iOS 有意义,进入 PiP 后声音交给影子)。
|
||||
Future<void> unmute() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('unmute');
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// iOS 画中画内换集:影子只换播放项,窗口不中断。
|
||||
Future<void> replaceItem({required String url, required int positionMs}) async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('replaceItem', {
|
||||
'url': url,
|
||||
'positionMs': positionMs,
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 请求退出画中画(iOS;触发 onPipChanged(false) 后由 Dart 收尾)。
|
||||
Future<void> stop() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('stop');
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// 销毁影子播放器(仅 iOS)。
|
||||
Future<void> teardown() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.iOS || kIsWeb) return;
|
||||
try {
|
||||
await _channel.invokeMethod<void>('teardown');
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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) ?? '';
|
||||
|
||||
@@ -6,6 +6,8 @@ import '../../config/app_config.dart';
|
||||
import '../models/content_category.dart';
|
||||
import '../models/drama.dart';
|
||||
import '../models/home_feed.dart';
|
||||
import '../models/page_result.dart';
|
||||
import '../remote/category_api.dart';
|
||||
import '../repositories/category_repository.dart';
|
||||
|
||||
/// 剧场页数据:服务端分类清单与发现 feed。
|
||||
@@ -14,13 +16,80 @@ class CategoryController extends ChangeNotifier {
|
||||
|
||||
final CategoryRepository _repository;
|
||||
|
||||
/// 生产环境注入。未注入时首页分类继续用本地筛选。
|
||||
Future<PageResult<Drama>> Function(
|
||||
String categoryId, {
|
||||
int pageIndex,
|
||||
int pageSize,
|
||||
})? dramaPageLoader;
|
||||
|
||||
List<ContentCategory> categories = const [];
|
||||
final Map<String, CategoryDramaSlot> _slots = {};
|
||||
HomeFeed feed = const HomeFeed();
|
||||
bool loading = false;
|
||||
String? error;
|
||||
String? debugError;
|
||||
bool _disposed = false;
|
||||
|
||||
/// 某个分类自己的短剧分页,不和别的分类共用。
|
||||
CategoryDramaSlot slotOf(String categoryId) {
|
||||
return _slots.putIfAbsent(categoryId, CategoryDramaSlot.new);
|
||||
}
|
||||
|
||||
/// 打开分类并加载第一页短剧。
|
||||
Future<void> openCategory(String categoryId) async {
|
||||
final loader = dramaPageLoader;
|
||||
if (loader == null) return;
|
||||
final slot = slotOf(categoryId);
|
||||
slot.loading = true;
|
||||
slot.loadingMore = false;
|
||||
_notify();
|
||||
try {
|
||||
final page = await loader(
|
||||
categoryId,
|
||||
pageIndex: 1,
|
||||
pageSize: CategoryApi.dramaPageSize,
|
||||
);
|
||||
slot.dramas = page.list;
|
||||
slot.total = page.total;
|
||||
slot.pageIndex = 1;
|
||||
} catch (exception) {
|
||||
if (kDebugMode) debugPrint('[category] $exception');
|
||||
} finally {
|
||||
slot.loading = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// 上拉加载这个分类的下一页。
|
||||
Future<void> loadMore(String categoryId) async {
|
||||
final loader = dramaPageLoader;
|
||||
final slot = _slots[categoryId];
|
||||
if (loader == null || slot == null) return;
|
||||
if (slot.loading || slot.loadingMore || !slot.hasMore) return;
|
||||
slot.loadingMore = true;
|
||||
_notify();
|
||||
try {
|
||||
final page = await loader(
|
||||
categoryId,
|
||||
pageIndex: slot.pageIndex + 1,
|
||||
pageSize: CategoryApi.dramaPageSize,
|
||||
);
|
||||
if (page.list.isEmpty) {
|
||||
slot.total = slot.dramas.length;
|
||||
} else {
|
||||
slot.dramas = [...slot.dramas, ...page.list];
|
||||
slot.total = page.total;
|
||||
slot.pageIndex += 1;
|
||||
}
|
||||
} catch (exception) {
|
||||
if (kDebugMode) debugPrint('[category] more $exception');
|
||||
} finally {
|
||||
slot.loadingMore = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// 分类九宫格点击后读取该分类的剧目;缺失分区返回空列表。
|
||||
List<Drama> dramasOf(String categoryId) {
|
||||
final code = 'category-$categoryId';
|
||||
@@ -30,19 +99,23 @@ class CategoryController extends ChangeNotifier {
|
||||
return const [];
|
||||
}
|
||||
|
||||
/// 加载分类与发现 feed;失败保留可重试错误态。
|
||||
/// 首页只拉分类,再拉第一个分类的短剧。发现页聚合留到没有短剧分页时再取。
|
||||
Future<void> load() async {
|
||||
loading = true;
|
||||
error = null;
|
||||
debugError = null;
|
||||
_notify();
|
||||
try {
|
||||
final results = await Future.wait<Object>([
|
||||
_repository.fetchCategories(),
|
||||
_repository.fetchDiscoverFeed(),
|
||||
]);
|
||||
categories = results[0] as List<ContentCategory>;
|
||||
feed = results[1] as HomeFeed;
|
||||
if (dramaPageLoader != null) {
|
||||
categories = await _repository.fetchCategories();
|
||||
} else {
|
||||
final results = await Future.wait<Object>([
|
||||
_repository.fetchCategories(),
|
||||
_repository.fetchDiscoverFeed(),
|
||||
]);
|
||||
categories = results[0] as List<ContentCategory>;
|
||||
feed = results[1] as HomeFeed;
|
||||
}
|
||||
} catch (exception) {
|
||||
error = 'categoriesError';
|
||||
debugError = exception.toString();
|
||||
@@ -53,6 +126,9 @@ class CategoryController extends ChangeNotifier {
|
||||
loading = false;
|
||||
_notify();
|
||||
}
|
||||
if (error == null && dramaPageLoader != null && categories.isNotEmpty) {
|
||||
await openCategory(categories.first.id);
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
@@ -65,3 +141,14 @@ class CategoryController extends ChangeNotifier {
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个分类的短剧分页状态。
|
||||
class CategoryDramaSlot {
|
||||
List<Drama> dramas = const [];
|
||||
int total = 0;
|
||||
int pageIndex = 0;
|
||||
bool loading = false;
|
||||
bool loadingMore = false;
|
||||
|
||||
bool get hasMore => dramas.length < total;
|
||||
}
|
||||
@@ -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,53 @@
|
||||
// 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;
|
||||
// 只有两端原生侧实现了 region;其它平台(测试、桌面)上通道没有 handler,
|
||||
// 调用会一直挂着,注册流程会卡在"转圈"。
|
||||
if (!Platform.isAndroid && !Platform.isIOS) 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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
part of 'playback_session.dart';
|
||||
|
||||
/// 当前集加上一集、下一集,切集时最多三个解码器。
|
||||
const int maxLivePlayers = 3;
|
||||
|
||||
/// 另一条播放路由必须等当前路由释放完全部原生播放器。
|
||||
class PlaybackCoordinator {
|
||||
PlaybackSession? _owner;
|
||||
Future<void> _handoff = Future<void>.value();
|
||||
|
||||
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) {
|
||||
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>((_) {});
|
||||
return result;
|
||||
}
|
||||
|
||||
void _forget(PlaybackSession session) {
|
||||
if (_owner == session && session.livePlayerCount == 0) _owner = null;
|
||||
}
|
||||
}
|
||||
|
||||
_PlayerSlot? _usableWarm(
|
||||
PlaybackSession session,
|
||||
_PlayerSlot? slot,
|
||||
int index,
|
||||
) {
|
||||
if (slot == null || slot.index != index || slot.failure != null) return null;
|
||||
if (session.isLocked) return null;
|
||||
return slot;
|
||||
}
|
||||
|
||||
/// 滑走的一集若仍是相邻集,就留着最后一帧,其余槽位释放。
|
||||
Future<void> _parkNeighbors(
|
||||
PlaybackSession session,
|
||||
_PlayerSlot? old,
|
||||
_PlayerSlot? warmNext,
|
||||
_PlayerSlot? warmPrevious,
|
||||
) async {
|
||||
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, {
|
||||
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;
|
||||
}
|
||||
if (session._previous == null && slot.index == session._previousIndex) {
|
||||
session._previous = slot;
|
||||
return;
|
||||
}
|
||||
await session._retire(slot, trigger: 'park-neighbor', roleHint: roleHint);
|
||||
}
|
||||
|
||||
/// 当前集已经出画后,按手势方向静默准备上一集和下一集。
|
||||
void _warmNeighbors(PlaybackSession session, {bool preferredNext = true}) {
|
||||
final request = session._generation;
|
||||
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(
|
||||
PlaybackSession session,
|
||||
int request,
|
||||
int? index, {
|
||||
required bool next,
|
||||
}) async {
|
||||
final candidate = await _allocateNeighbor(
|
||||
session,
|
||||
request,
|
||||
index,
|
||||
next: next,
|
||||
);
|
||||
if (candidate == null) return;
|
||||
await candidate.ready;
|
||||
if (session._closed || !_stillHeld(session, candidate, next: next)) return;
|
||||
if (candidate.failure == null) {
|
||||
session._notify();
|
||||
return;
|
||||
}
|
||||
await session._enqueue(() async {
|
||||
if (!_stillHeld(session, candidate, next: next)) return;
|
||||
_clearNeighbor(session, next: next);
|
||||
await session._retire(
|
||||
candidate,
|
||||
trigger: 'warm-failure',
|
||||
roleHint: next ? 'next' : 'previous',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<_PlayerSlot?> _allocateNeighbor(
|
||||
PlaybackSession session,
|
||||
int request,
|
||||
int? index, {
|
||||
required bool next,
|
||||
}) async {
|
||||
_PlayerSlot? created;
|
||||
await session._enqueue(() async {
|
||||
if (session._closed || request != session._generation) return;
|
||||
final allowed = _neighborAllowed(session, index);
|
||||
final current = next ? session._next : session._previous;
|
||||
if (!allowed || current?.index != index) {
|
||||
_clearNeighbor(session, next: next);
|
||||
await session._retire(
|
||||
current,
|
||||
trigger: 'warm-slot-invalid',
|
||||
roleHint: next ? 'next' : 'previous',
|
||||
);
|
||||
}
|
||||
if (!_canAllocate(session, request, allowed: allowed, next: next)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
created = session._create(index!);
|
||||
} on StateError catch (error) {
|
||||
if (kDebugMode) debugPrint('相邻集预热跳过: $error');
|
||||
return;
|
||||
}
|
||||
if (next) {
|
||||
session._next = created;
|
||||
} else {
|
||||
session._previous = created;
|
||||
}
|
||||
});
|
||||
return created;
|
||||
}
|
||||
|
||||
bool _neighborAllowed(PlaybackSession session, int? index) {
|
||||
return index != null &&
|
||||
index >= 0 &&
|
||||
index < session.episodes.length &&
|
||||
index != session._currentIndex &&
|
||||
session.canPlay(session.episodes[index]);
|
||||
}
|
||||
|
||||
bool _canAllocate(
|
||||
PlaybackSession session,
|
||||
int request, {
|
||||
required bool allowed,
|
||||
required bool next,
|
||||
}) {
|
||||
final held = next ? session._next : session._previous;
|
||||
return session._visible &&
|
||||
!session._overlayOpen &&
|
||||
request == session._generation &&
|
||||
session._active?.prepared == true &&
|
||||
allowed &&
|
||||
held == null;
|
||||
}
|
||||
|
||||
bool _stillHeld(
|
||||
PlaybackSession session,
|
||||
_PlayerSlot slot, {
|
||||
required bool next,
|
||||
}) {
|
||||
return (next ? session._next : session._previous) == slot;
|
||||
}
|
||||
|
||||
void _clearNeighbor(PlaybackSession session, {required bool next}) {
|
||||
if (next) {
|
||||
session._next = null;
|
||||
return;
|
||||
}
|
||||
session._previous = null;
|
||||
}
|
||||
@@ -7,44 +7,19 @@ import '../models/drama.dart';
|
||||
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);
|
||||
const Duration _qualityHandoffHold = Duration(milliseconds: 500);
|
||||
|
||||
typedef PlayerFactory = PlayerPort Function(Episode episode);
|
||||
typedef PlayerPreparation =
|
||||
Future<void> Function(Episode episode, PlayerPort player);
|
||||
|
||||
/// Shared by routes: the previous session releases all native players before
|
||||
/// another session allocates. The app therefore has at most two, not two per page.
|
||||
class PlaybackCoordinator {
|
||||
PlaybackSession? _owner;
|
||||
Future<void> _handoff = Future<void>.value();
|
||||
enum PlaybackSessionOwner { home, player }
|
||||
|
||||
Future<bool> _acquire(PlaybackSession session, bool Function() valid) {
|
||||
final result = _handoff.then((_) async {
|
||||
if (!valid()) return false;
|
||||
if (_owner != session) {
|
||||
final previous = _owner;
|
||||
await previous?._releasePlayers();
|
||||
// A failed native disposal cannot be treated as a free decoder slot.
|
||||
if (previous != null && previous.livePlayerCount != 0) return false;
|
||||
_owner = null;
|
||||
if (!valid()) return false;
|
||||
_owner = session;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
_handoff = result.then<void>((_) {});
|
||||
return result;
|
||||
}
|
||||
|
||||
void _forget(PlaybackSession session) {
|
||||
if (_owner == session && session.livePlayerCount == 0) _owner = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns current + one prepared successor. All allocation, playback and disposal
|
||||
/// operations are serialized; initialization can run while current plays.
|
||||
/// Owns current plus previous/next frames; allocation stays serialized.
|
||||
class PlaybackSession extends ChangeNotifier {
|
||||
PlaybackSession({
|
||||
required this.episodes,
|
||||
@@ -54,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;
|
||||
@@ -66,16 +43,20 @@ 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;
|
||||
_PlayerSlot? _next;
|
||||
_PlayerSlot? _previous;
|
||||
_PlayerSlot? _handoff;
|
||||
Future<void> _operations = Future<void>.value();
|
||||
Future<void> _preloadTask = Future<void>.value();
|
||||
int _generation = 0;
|
||||
int _currentIndex = 0;
|
||||
int? _nextIndex;
|
||||
int? _previousIndex;
|
||||
bool _selected = false;
|
||||
bool _loading = false;
|
||||
bool _closed = false;
|
||||
@@ -103,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;
|
||||
|
||||
@@ -120,7 +110,7 @@ class PlaybackSession extends ChangeNotifier {
|
||||
/// during a swipe without starting audio or registering history listeners.
|
||||
PlayerPort? preparedPlayerAt(int index) {
|
||||
if (_closed) return null;
|
||||
for (final slot in [_active, _next]) {
|
||||
for (final slot in [_active, _next, _previous]) {
|
||||
if (slot == null ||
|
||||
slot.retiring ||
|
||||
slot.index != index ||
|
||||
@@ -132,34 +122,41 @@ 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}) {
|
||||
void remapCurrentIndex(int index, {int? preloadIndex, int? previousIndex}) {
|
||||
if (_closed || index < 0 || index >= episodes.length) return;
|
||||
final activeSlot = _active;
|
||||
if (activeSlot == null || activeSlot.index != _currentIndex) {
|
||||
_currentIndex = index;
|
||||
_nextIndex = preloadIndex;
|
||||
_rememberNeighbors(preloadIndex, previousIndex);
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
_generation++;
|
||||
activeSlot.index = index;
|
||||
_currentIndex = index;
|
||||
_nextIndex = preloadIndex;
|
||||
_rememberNeighbors(preloadIndex, previousIndex);
|
||||
final staleNext = _next;
|
||||
final stalePrevious = _previous;
|
||||
_next = null;
|
||||
_previous = null;
|
||||
_notify();
|
||||
unawaited(_enqueue(() async => _retire(staleNext)));
|
||||
if (_visible && !_overlayOpen) _schedulePreload();
|
||||
unawaited(
|
||||
_enqueue(() async {
|
||||
await _retire(staleNext, trigger: 'remap-stale-next', roleHint: 'next');
|
||||
await _retire(
|
||||
stalePrevious,
|
||||
trigger: 'remap-stale-previous',
|
||||
roleHint: 'previous',
|
||||
);
|
||||
}),
|
||||
);
|
||||
if (_visible && !_overlayOpen) _warmNeighbors(this);
|
||||
}
|
||||
|
||||
void _rememberNeighbors(int? preloadIndex, int? previousIndex) {
|
||||
_nextIndex = preloadIndex;
|
||||
_previousIndex = previousIndex;
|
||||
}
|
||||
|
||||
Future<void> _enqueue(Future<void> Function() operation) {
|
||||
@@ -176,8 +173,15 @@ class PlaybackSession extends ChangeNotifier {
|
||||
}
|
||||
|
||||
_PlayerSlot _create(int index) {
|
||||
if (_live.length >= 2) throw StateError('Playback resource limit reached');
|
||||
final slot = _PlayerSlot(index, factory(episodes[index]));
|
||||
if (_live.length >= maxLivePlayers) {
|
||||
throw StateError('Playback resource limit reached');
|
||||
}
|
||||
final slot = _PlayerSlot(
|
||||
index,
|
||||
factory(episodes[index]),
|
||||
owner: owner,
|
||||
dramaId: dramaIdAt?.call(index),
|
||||
);
|
||||
_live.add(slot);
|
||||
slot.ready = () async {
|
||||
try {
|
||||
@@ -195,12 +199,32 @@ 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 || _next == slot || _handoff == slot;
|
||||
final cleared =
|
||||
_active == slot ||
|
||||
_next == slot ||
|
||||
_previous == slot ||
|
||||
_handoff == slot;
|
||||
if (_active == slot) _active = null;
|
||||
if (_next == slot) _next = null;
|
||||
if (_previous == slot) _previous = null;
|
||||
if (_handoff == slot) _handoff = null;
|
||||
if (cleared) _notify();
|
||||
await waitForFrame?.call();
|
||||
@@ -210,22 +234,51 @@ 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',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// preloadIndex comes from the visible queue, so filtered categories and series
|
||||
/// use exactly the same mechanism without warming an unrelated episode.
|
||||
Future<void> select(int index, {int? preloadIndex}) async {
|
||||
Future<void> select(
|
||||
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;
|
||||
_selected = true;
|
||||
_currentIndex = index;
|
||||
_nextIndex = preloadIndex;
|
||||
_rememberNeighbors(preloadIndex, previousIndex);
|
||||
_error = null;
|
||||
if (!_visible) {
|
||||
_loading = false;
|
||||
@@ -250,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 &&
|
||||
@@ -259,20 +312,27 @@ class PlaybackSession extends ChangeNotifier {
|
||||
target = old;
|
||||
return;
|
||||
}
|
||||
if (old != null) await old.player.pause();
|
||||
final warm = _next;
|
||||
if (old != null) {
|
||||
await old.player.pause();
|
||||
old.playing = false;
|
||||
}
|
||||
final warmNext = _next;
|
||||
final warmPrevious = _previous;
|
||||
_active = null;
|
||||
_next = null;
|
||||
final hit = warm?.index == index && warm?.failure == null && !isLocked;
|
||||
if (hit) {
|
||||
_previous = null;
|
||||
final warm =
|
||||
_usableWarm(this, warmNext, index) ??
|
||||
_usableWarm(this, warmPrevious, index);
|
||||
if (warm != null) {
|
||||
warm.reusedWarm = true;
|
||||
target = _active = warm;
|
||||
_loading = !warm!.prepared;
|
||||
_loading = !warm.prepared;
|
||||
_notify();
|
||||
// Start a ready successor before awaiting slow disposal of the old one.
|
||||
if (warm.prepared) await _start(warm, request);
|
||||
}
|
||||
await _retire(old);
|
||||
if (!hit) await _retire(warm);
|
||||
await _parkNeighbors(this, old, warmNext, warmPrevious);
|
||||
if (_closed || request != _generation || isLocked) return;
|
||||
if (target == null) {
|
||||
target = _active = _create(index);
|
||||
@@ -285,7 +345,7 @@ class PlaybackSession extends ChangeNotifier {
|
||||
await slot.ready;
|
||||
if (_closed || request != _generation || _active != slot) return;
|
||||
await _enqueue(() => _start(slot, request));
|
||||
if (!_closed && request == _generation) _schedulePreload();
|
||||
if (!_closed && request == _generation) _warmNeighbors(this);
|
||||
}
|
||||
|
||||
/// 后台准备新片源,成功后再替换当前播放器。失败时原播放器保持不动。
|
||||
@@ -314,9 +374,11 @@ 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) _schedulePreload();
|
||||
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,96 +503,42 @@ class PlaybackSession extends ChangeNotifier {
|
||||
await slot.player.pause();
|
||||
}
|
||||
slot.playing = shouldPlay;
|
||||
}
|
||||
|
||||
void _schedulePreload() {
|
||||
final request = _generation;
|
||||
final index = _nextIndex;
|
||||
_preloadTask = () async {
|
||||
_PlayerSlot? candidate;
|
||||
await _enqueue(() async {
|
||||
if (_closed || request != _generation) return;
|
||||
final allowed =
|
||||
index != null &&
|
||||
index >= 0 &&
|
||||
index < episodes.length &&
|
||||
index != _currentIndex &&
|
||||
canPlay(episodes[index]);
|
||||
if (!allowed || _next?.index != index) {
|
||||
final stale = _next;
|
||||
_next = null;
|
||||
await _retire(stale);
|
||||
}
|
||||
if (!_visible ||
|
||||
_overlayOpen ||
|
||||
request != _generation ||
|
||||
_active?.prepared != true ||
|
||||
!allowed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
candidate = _next ??= _create(index);
|
||||
} catch (_) {
|
||||
// Optional allocation failure must not interrupt the playing item.
|
||||
}
|
||||
});
|
||||
final slot = candidate;
|
||||
if (slot == null) return;
|
||||
await slot.ready;
|
||||
if (_closed || _next != slot) return;
|
||||
if (slot.failure != null) {
|
||||
// Optional work fails silently. A later explicit selection retries.
|
||||
await _enqueue(() async {
|
||||
if (_next != slot) return;
|
||||
_next = null;
|
||||
await _retire(slot);
|
||||
});
|
||||
} else {
|
||||
_notify();
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
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() {
|
||||
if (_closed) return;
|
||||
if (_visible && _selected && active == null) {
|
||||
unawaited(select(_currentIndex, preloadIndex: _nextIndex));
|
||||
unawaited(
|
||||
select(
|
||||
_currentIndex,
|
||||
preloadIndex: _nextIndex,
|
||||
previousIndex: _previousIndex,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final slot = _active;
|
||||
if (slot != null) unawaited(_enqueue(() => _applyPlayback(slot)));
|
||||
if (_visible && !_overlayOpen && !_loading) _schedulePreload();
|
||||
if (_visible && !_overlayOpen && !_loading) _warmNeighbors(this);
|
||||
}
|
||||
|
||||
Future<void> _releasePlayers() {
|
||||
_generation++;
|
||||
return _enqueue(() async {
|
||||
_active = _next = _handoff = null;
|
||||
_active = _next = _previous = _handoff = null;
|
||||
_loading = false;
|
||||
_notify();
|
||||
for (final slot in _live.toList()) {
|
||||
await _retire(slot);
|
||||
await _retire(slot, trigger: 'session-release-all');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -518,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;
|
||||
@@ -528,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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/playlist_detail.dart';
|
||||
import '../remote/catalog_api.dart';
|
||||
import '../repositories/playlist_repository.dart';
|
||||
|
||||
/// 推荐页剧单:已启用剧单及其短剧卡片。
|
||||
class PlaylistController extends ChangeNotifier {
|
||||
PlaylistController(this._repository);
|
||||
|
||||
final PlaylistRepository _repository;
|
||||
|
||||
static const int pageSize = CatalogApi.playlistPageSize;
|
||||
|
||||
List<PlaylistDetail> items = const [];
|
||||
bool loading = false;
|
||||
bool loadingMore = false;
|
||||
bool loaded = false;
|
||||
bool hasMore = false;
|
||||
String? error;
|
||||
int _pageIndex = 1;
|
||||
bool _disposed = false;
|
||||
|
||||
/// 从第一页重新拉取。失败保留错误态,成功后替换本地缓存。
|
||||
Future<void> load() async {
|
||||
loading = true;
|
||||
error = null;
|
||||
_notify();
|
||||
try {
|
||||
final page = await _repository.fetchPlaylists(pageSize: pageSize);
|
||||
items = page.list;
|
||||
_pageIndex = 1;
|
||||
hasMore = items.length < page.total;
|
||||
loaded = true;
|
||||
} catch (exception) {
|
||||
error = 'playlistsError';
|
||||
if (kDebugMode) debugPrint('[playlist] $exception');
|
||||
} finally {
|
||||
loading = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// 滚到底时追加下一页。没有更多或正在请求时直接返回。
|
||||
Future<void> loadMore() async {
|
||||
if (loading || loadingMore || !hasMore) return;
|
||||
loadingMore = true;
|
||||
_notify();
|
||||
try {
|
||||
final page = await _repository.fetchPlaylists(
|
||||
pageIndex: _pageIndex + 1,
|
||||
pageSize: pageSize,
|
||||
);
|
||||
if (page.list.isEmpty) {
|
||||
hasMore = false;
|
||||
} else {
|
||||
items = [...items, ...page.list];
|
||||
_pageIndex += 1;
|
||||
hasMore = items.length < page.total;
|
||||
}
|
||||
} catch (exception) {
|
||||
if (kDebugMode) debugPrint('[playlist] more $exception');
|
||||
} finally {
|
||||
loadingMore = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// 打开某一剧单时再取一次详情;失败则回落到列表里已有的那条。
|
||||
Future<PlaylistDetail> detail(
|
||||
String id, {
|
||||
int pageIndex = 1,
|
||||
int pageSize = CatalogApi.playlistDramaPageSize,
|
||||
}) async {
|
||||
try {
|
||||
return await _repository.fetchPlaylist(
|
||||
id,
|
||||
pageIndex: pageIndex,
|
||||
pageSize: pageSize,
|
||||
);
|
||||
} catch (exception) {
|
||||
if (kDebugMode) debugPrint('[playlist] detail $id $exception');
|
||||
return items.firstWhere(
|
||||
(item) => item.id == id,
|
||||
orElse: () => PlaylistDetail(
|
||||
id: id,
|
||||
name: '',
|
||||
description: '',
|
||||
dramaCount: 0,
|
||||
dramas: const [],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
@@ -139,6 +144,14 @@ class WatchRecordsController extends ChangeNotifier {
|
||||
return _detailCache[dramaId];
|
||||
}
|
||||
|
||||
/// 按剧集 id 找最近观看记录,供收藏网格显示「看到第n集」与继续观看横幅。
|
||||
WatchRecord? recordForDrama(String dramaId) {
|
||||
for (final record in records) {
|
||||
if (record.dramaId == dramaId) return record;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 删除单条记录,先更新 UI,失败按原位置回滚。
|
||||
Future<bool> remove(String dramaId) async {
|
||||
final index = _recordIndex(dramaId);
|
||||
@@ -148,17 +161,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 +194,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 +322,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;
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
@@ -8,7 +8,7 @@ String localizedDramaTitle(AppLocalizations l10n, Drama drama) =>
|
||||
'the-signal-demo' => l10n.dramaSignalTitle,
|
||||
'city-lights-demo' => l10n.dramaCityTitle,
|
||||
'vengeance-demo' => l10n.dramaVengeanceTitle,
|
||||
_ => drama.title,
|
||||
_ => drama.localizedTitle(l10n.localeName.split(RegExp(r'[_-]')).first),
|
||||
};
|
||||
|
||||
String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
|
||||
@@ -16,7 +16,7 @@ String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
|
||||
'the-signal-demo' => l10n.dramaSignalSynopsis,
|
||||
'city-lights-demo' => l10n.dramaCitySynopsis,
|
||||
'vengeance-demo' => l10n.dramaVengeanceSynopsis,
|
||||
_ => drama.synopsis,
|
||||
_ => drama.localizedSynopsis(l10n.localeName.split(RegExp(r'[_-]')).first),
|
||||
};
|
||||
|
||||
String localizedEpisodeTitle(AppLocalizations l10n, int number) =>
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// iOS 首次启动等待系统无线数据选择,再发首个接口请求。
|
||||
abstract final class WirelessDataPrompt {
|
||||
const WirelessDataPrompt._();
|
||||
|
||||
/// 系统选择超过此时长仍未回调时继续启动。
|
||||
static const Duration decisionTimeout = Duration(seconds: 15);
|
||||
|
||||
/// 与 iOS `WirelessDataPrompt.channelName` 保持一致。
|
||||
static const String channelName = 'com.stormg.lumadrama/wireless-data';
|
||||
|
||||
static const String _awaitDecisionMethod = 'awaitDecision';
|
||||
|
||||
static const MethodChannel _channel = MethodChannel(channelName);
|
||||
|
||||
static Future<void>? _pending;
|
||||
|
||||
/// 非 iOS 立即返回。iOS 只等待一次,失败或超时后放行。
|
||||
static Future<void> awaitDecision({
|
||||
required bool enabled,
|
||||
Future<void> Function()? ask,
|
||||
Duration? timeout,
|
||||
}) {
|
||||
if (!enabled) return Future<void>.value();
|
||||
return _pending ??= _askOnce(ask, timeout ?? decisionTimeout);
|
||||
}
|
||||
|
||||
/// 测试隔离用,清掉已完成的等待。
|
||||
@visibleForTesting
|
||||
static void resetForTest() {
|
||||
_pending = null;
|
||||
}
|
||||
|
||||
static Future<void> _askOnce(
|
||||
Future<void> Function()? ask,
|
||||
Duration timeout,
|
||||
) async {
|
||||
try {
|
||||
await (ask ?? _invokeChannel).call().timeout(timeout);
|
||||
} on TimeoutException {
|
||||
_log('decision timed out');
|
||||
} catch (error) {
|
||||
_log('decision skipped: $error');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _invokeChannel() {
|
||||
return _channel.invokeMethod<void>(_awaitDecisionMethod);
|
||||
}
|
||||
|
||||
static void _log(String message) {
|
||||
if (kDebugMode) {
|
||||
debugPrint('[wireless-data] $message');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,13 +27,13 @@ abstract final class AppColors {
|
||||
static const overlaySecondary = Color(0xFFC7C7CC);
|
||||
static const overlayLabel = Color(0xFFE6E6EB);
|
||||
|
||||
/// 主操作、选中态、播放进度(品牌橙)。
|
||||
static const blue = Color(0xFFFF6B2C);
|
||||
/// 主操作、选中态、播放进度。旧品牌橙已全量映射为品牌红(2026-10 改版)。
|
||||
static const blue = Color(0xFFF04E4E);
|
||||
static const primary = blue;
|
||||
static const actionRed = Color(0xFFFF3B30);
|
||||
|
||||
/// 主操作按下态。
|
||||
static const bluePressed = Color(0xFFE55A1F);
|
||||
static const bluePressed = Color(0xFFD64040);
|
||||
|
||||
/// 链接与次要高亮:统一改用中性浅灰,避免旧青色残留。
|
||||
static const blueSoft = Color(0xFFB0B0B0);
|
||||
@@ -47,6 +47,10 @@ abstract final class AppColors {
|
||||
static const homeGiftPink = Color(0xFFFF4D8D);
|
||||
static const vipGoldStart = Color(0xFFF5D9A0);
|
||||
static const vipGoldEnd = Color(0xFFE8B65A);
|
||||
|
||||
/// 「我的」页 VIP 卡的浅香槟金(见设计稿,接近纯色)。
|
||||
static const vipCardStart = Color(0xFFF6E8C6);
|
||||
static const vipCardEnd = Color(0xFFEDD9A8);
|
||||
static const vipBadgeSurface = Color(0x1F3D2408);
|
||||
static const bronze = Color(0xFFCD7F32);
|
||||
static const bronzeDeep = Color(0xFFA9713A);
|
||||
@@ -75,10 +79,24 @@ abstract final class AppColors {
|
||||
/// 首页/追剧/我的统一的纯黑内容背景。
|
||||
static const appBackground = Color(0xFF000000);
|
||||
|
||||
/// 追剧页顶部的暗红光晕,向下淡入纯黑(见设计稿)。
|
||||
static const followingGlow = Color(0xFF4C161A);
|
||||
|
||||
/// 光晕的过渡色:让暖色维持更久再压黑。
|
||||
static const followingGlowMid = Color(0xFF1E0B0C);
|
||||
|
||||
/// 继续观看横幅剧名的暖白(见设计稿,非纯白)。
|
||||
static const bannerTitleWarm = Color(0xFFF5EFE4);
|
||||
|
||||
/// 中性深灰卡片与控件表面。
|
||||
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);
|
||||
@@ -91,7 +109,7 @@ abstract final class AppColors {
|
||||
static const mineGradientTop = Color(0xFF3A1B0E);
|
||||
static const mineGradientMiddle = Color(0xFF1A0C07);
|
||||
static const mineGradientBottom = Color(0xFF000000);
|
||||
static const mineGradientGlow = Color(0x33FF6B2C);
|
||||
static const mineGradientGlow = Color(0x33F04E4E);
|
||||
static const mineGridSurface = Color(0x99101010);
|
||||
static const minePanelSurface = Color(0xFF101010);
|
||||
static const mineMoreDivider = Color(0xFF1C1C1E);
|
||||
@@ -106,12 +124,15 @@ abstract final class AppColors {
|
||||
static const mineIconLanguage = Color(0xFF22D3EE);
|
||||
static const mineIconSettings = Color(0xFFA1A1AA);
|
||||
static const mineIconNotices = Color(0xFFFF8A4C);
|
||||
static const recommendPlaylistGlow = Color(0x26FF6B2C);
|
||||
static const recommendPlaylistGlow = Color(0x26F04E4E);
|
||||
|
||||
/// 次级文字与列表 chevron。
|
||||
static const textPrimary = Color(0xFFFFFFFF);
|
||||
static const textSecondary = Color(0xFFB0B0B0);
|
||||
static const textTertiary = Color(0xFF8E8E93);
|
||||
|
||||
/// 列表底部「没有更多了」这类弱提示。
|
||||
static const textHint = Color(0xFF5C5C60);
|
||||
static const textTabInactive = Color(0xFFB0B0B0);
|
||||
static const textFilterIcon = Color(0xFF7A7A7E);
|
||||
static const searchResultMeta = Color(0xFF9E9E9E);
|
||||
@@ -125,9 +146,11 @@ 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 brandRedPressed = Color(0xFFD64040);
|
||||
static const navSelected = brandRed;
|
||||
|
||||
/// 卡片阴影(深色几乎不用阴影)。
|
||||
static const cardShadow = Color(0x00000000);
|
||||
@@ -180,8 +203,8 @@ abstract final class AppColors {
|
||||
/// 封面集数胶囊。
|
||||
static const badgeBeige = raised;
|
||||
|
||||
/// 导航未选中。
|
||||
static const navUnselected = textSecondary;
|
||||
/// 导航未选中(设计稿为白色线框 + 白色文字)。
|
||||
static const navUnselected = Color(0xFFFFFFFF);
|
||||
|
||||
/// 首页内容角标。
|
||||
static const badgeHot = Color(0xFFE5484D);
|
||||
@@ -205,7 +228,7 @@ abstract final class AppColors {
|
||||
static const bannerScrimEnd = Color(0xE6000000);
|
||||
|
||||
/// 票券虚线等主色描边。
|
||||
static const primaryBorder = Color(0x66FF6B2C);
|
||||
static const primaryBorder = Color(0x66F04E4E);
|
||||
|
||||
static const outlineDark = border;
|
||||
static const outlineVariantDark = border;
|
||||
|
||||
@@ -146,10 +146,12 @@ abstract final class AppDimens {
|
||||
static const double homeActionGap = 6;
|
||||
|
||||
/// 推荐分区。
|
||||
static const double recommendSectionGap = 12;
|
||||
static const double recommendSectionTitle = 17;
|
||||
static const double recommendSectionSubtitle = 11;
|
||||
static const double recommendSectionMore = 12;
|
||||
static const double recommendRowHeight = 252;
|
||||
// 封面 122*(4/3)≈163 + 间距6 + 两行标题39 + 间距6 + 标签13 ≈ 227。
|
||||
static const double recommendRowHeight = 228;
|
||||
static const double recommendCardWidth = 122;
|
||||
|
||||
/// 首页热播榜。
|
||||
@@ -169,25 +171,27 @@ abstract final class AppDimens {
|
||||
|
||||
/// 全部短剧筛选与追剧双列。
|
||||
static const double filterChipFont = 16;
|
||||
static const double filterChipHeight = 32;
|
||||
static const double filterChipRadius = 16;
|
||||
static const double filterChipHeight = 28;
|
||||
static const double filterChipRadius = 14;
|
||||
static const double filterChipHorizontalPadding = 12;
|
||||
static const double filterRowGap = 6;
|
||||
static const double filterItemGap = 10;
|
||||
static const double allDramasHorizontal = 12;
|
||||
static const double allDramasGridGap = 6;
|
||||
static const double allDramasGridRowGap = 12;
|
||||
static const double allDramasGridRowGap = 6;
|
||||
static const double allDramasFilterToGridGap = 12;
|
||||
static const double followingHeaderHeight = 52;
|
||||
static const double followingTabFont = 18;
|
||||
static const double followingTabGap = 24;
|
||||
static const double followingEditIconSize = 20;
|
||||
static const double followingEditHitSize = 40;
|
||||
static const double followingAddIconSize = 28;
|
||||
static const double followingAddIconSize = 20;
|
||||
static const double followingAddIconStroke = 1.5;
|
||||
static const double followingGridGap = 6;
|
||||
static const double followingGridRowGap = 12;
|
||||
static const double followingCardTextExtent = 70;
|
||||
// 单行标题 16*1.3=20.8 + 间距 6+4 + 副标题行高约 18.6 ≈ 49.4,留 0.6 余量;
|
||||
// 按 48 估算在副标题行高偏高的字体下会溢出 1~2px。
|
||||
static const double followingCardTextExtent = 50;
|
||||
static const double followingSubtitleFont = 12;
|
||||
static const double followingSubtitleGap = 4;
|
||||
static const double followingProgressHeight = 2;
|
||||
@@ -201,6 +205,47 @@ abstract final class AppDimens {
|
||||
static const double followingHistoryProgressGap = 8;
|
||||
static const double followingHistoryLabelGap = 4;
|
||||
static const double followingHistoryActionHeight = 28;
|
||||
|
||||
/// 追剧页新版头部与收藏布局。
|
||||
static const double followingTitleFont = 26;
|
||||
static const double followingTitleRowHeight = 42;
|
||||
static const double followingTitleTopGap = 8;
|
||||
static const double followingSearchIcon = 26;
|
||||
static const double followingManageFont = 16;
|
||||
static const double followingHeaderActionGap = 8;
|
||||
static const double followingSegmentFont = 16;
|
||||
static const double followingSegmentGap = 28;
|
||||
static const double followingSegmentRowHeight = 42;
|
||||
static const double followingSegmentIndicatorWidth = 24;
|
||||
static const double followingSegmentIndicatorHeight = 3;
|
||||
static const double followingSegmentIndicatorRadius = 2;
|
||||
static const double followingSegmentIndicatorTopGap = 6;
|
||||
static const double followingBannerHeight = 176;
|
||||
static const double followingBannerRadius = 16;
|
||||
static const double followingBannerEdgeGap = 16;
|
||||
static const double followingBannerInnerGap = 16;
|
||||
static const double followingBannerTitleFont = 22;
|
||||
static const double followingBannerSubtitleFont = 13;
|
||||
static const double followingBannerMetaGap = 8;
|
||||
static const double followingBannerButtonHeight = 40;
|
||||
static const double followingBannerButtonRadius = 20;
|
||||
static const double followingBannerButtonFont = 15;
|
||||
static const double followingBannerButtonIcon = 18;
|
||||
static const double followingBannerButtonGap = 6;
|
||||
static const double followingBannerButtonHorizontalPadding = 20;
|
||||
static const double followingBannerButtonTopGap = 14;
|
||||
static const double followingBannerProgressHeight = 3;
|
||||
static const double followingSectionTitleFont = 16;
|
||||
static const double followingSectionCountFont = 13;
|
||||
static const double followingSectionTopGap = 20;
|
||||
static const double followingSectionBottomGap = 12;
|
||||
static const double followingCardTitleFontNew = 16;
|
||||
static const double followingCardSubtitleFontNew = 13;
|
||||
static const double followingBadgeFont = 11;
|
||||
static const double followingBadgeRadius = 6;
|
||||
static const double followingBadgeInset = 8;
|
||||
static const double followingBadgePaddingH = 8;
|
||||
static const double followingBadgePaddingV = 3;
|
||||
static const Duration followingTabAnimationDuration = Duration(
|
||||
milliseconds: 180,
|
||||
);
|
||||
@@ -211,8 +256,8 @@ abstract final class AppDimens {
|
||||
/// 「我的」页中性视觉。
|
||||
static const double mineCardRadius = 16;
|
||||
static const double mineSectionTitle = 15;
|
||||
static const double mineAvatar = 56;
|
||||
static const double mineUserName = 20;
|
||||
static const double mineAvatar = 64;
|
||||
static const double mineUserName = 24;
|
||||
static const double mineUserNameLineHeight = 1.15;
|
||||
static const double mineUserNameUidGap = 2;
|
||||
static const double mineUid = 12;
|
||||
@@ -227,9 +272,25 @@ abstract final class AppDimens {
|
||||
static const double mineGridDividerWidth = 1;
|
||||
static const double mineSectionTitleFont = 16;
|
||||
static const double mineSectionLinkFont = 12;
|
||||
static const double mineSectionGap = 20;
|
||||
static const double mineSectionGap = 12;
|
||||
|
||||
/// 「我的」页新版:快捷图标行与服务列表。
|
||||
static const double mineQuickActionIcon = 28;
|
||||
static const double mineQuickActionLabelFont = 14;
|
||||
static const double mineQuickActionGap = 8;
|
||||
static const double mineServiceRowHeight = 56;
|
||||
static const double mineServiceIcon = 24;
|
||||
static const double mineServiceTitleFont = 16;
|
||||
static const double mineServiceValueFont = 14;
|
||||
static const double mineVipBenefitFont = 14;
|
||||
static const double mineVipBenefitIcon = 20;
|
||||
static const double mineVipBenefitBox = 30;
|
||||
static const double mineVipBenefitBoxRadius = 7;
|
||||
static const double mineVipBenefitGlyph = 17;
|
||||
static const double mineVipBenefitRowGap = 4;
|
||||
static const double mineVipButtonHeight = 36;
|
||||
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;
|
||||
|
||||
@@ -40,7 +40,7 @@ abstract final class AppTheme {
|
||||
/// 全局深色主题。
|
||||
static ThemeData dark() {
|
||||
const scheme = ColorScheme.dark(
|
||||
primary: AppColors.blue,
|
||||
primary: AppColors.brandRed,
|
||||
onPrimary: AppColors.onPrimary,
|
||||
secondary: AppColors.secondary,
|
||||
onSecondary: AppColors.ink,
|
||||
@@ -54,7 +54,7 @@ abstract final class AppTheme {
|
||||
outline: AppColors.border,
|
||||
outlineVariant: AppColors.border,
|
||||
surfaceTint: AppColors.transparent,
|
||||
inversePrimary: AppColors.bluePressed,
|
||||
inversePrimary: AppColors.brandRedPressed,
|
||||
error: AppColors.error,
|
||||
onError: AppColors.onPrimary,
|
||||
);
|
||||
@@ -66,16 +66,16 @@ abstract final class AppTheme {
|
||||
canvasColor: AppColors.ink,
|
||||
fontFamily: 'PlusJakartaSans',
|
||||
progressIndicatorTheme: const ProgressIndicatorThemeData(
|
||||
color: AppColors.blue,
|
||||
color: AppColors.brandRed,
|
||||
),
|
||||
sliderTheme: const SliderThemeData(
|
||||
activeTrackColor: AppColors.blue,
|
||||
activeTrackColor: AppColors.brandRed,
|
||||
inactiveTrackColor: AppColors.border,
|
||||
thumbColor: AppColors.onPrimary,
|
||||
),
|
||||
tabBarTheme: const TabBarThemeData(
|
||||
labelColor: AppColors.blue,
|
||||
indicatorColor: AppColors.blue,
|
||||
labelColor: AppColors.brandRed,
|
||||
indicatorColor: AppColors.brandRed,
|
||||
unselectedLabelColor: AppColors.muted,
|
||||
),
|
||||
textButtonTheme: TextButtonThemeData(
|
||||
@@ -138,12 +138,12 @@ abstract final class AppTheme {
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: _inputRadius,
|
||||
borderSide: const BorderSide(color: AppColors.blue),
|
||||
borderSide: const BorderSide(color: AppColors.brandRed),
|
||||
),
|
||||
),
|
||||
chipTheme: ChipThemeData(
|
||||
backgroundColor: AppColors.raised,
|
||||
selectedColor: AppColors.blue.withValues(alpha: 0.22),
|
||||
selectedColor: AppColors.brandRed.withValues(alpha: 0.22),
|
||||
labelStyle: const TextStyle(color: AppColors.onSurface),
|
||||
secondaryLabelStyle: const TextStyle(color: AppColors.muted),
|
||||
side: const BorderSide(color: AppColors.border),
|
||||
@@ -216,7 +216,7 @@ abstract final class AppTheme {
|
||||
),
|
||||
trackColor: WidgetStateProperty.resolveWith(
|
||||
(states) =>
|
||||
states.contains(WidgetState.selected) ? AppColors.blue : null,
|
||||
states.contains(WidgetState.selected) ? AppColors.brandRed : null,
|
||||
),
|
||||
),
|
||||
snackBarTheme: const SnackBarThemeData(
|
||||
@@ -273,8 +273,8 @@ abstract final class AppTheme {
|
||||
if (states.contains(WidgetState.pressed) ||
|
||||
states.contains(WidgetState.hovered) ||
|
||||
states.contains(WidgetState.focused)) {
|
||||
return AppColors.bluePressed;
|
||||
return AppColors.brandRedPressed;
|
||||
}
|
||||
return AppColors.blue;
|
||||
return AppColors.brandRed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/app_colors.dart';
|
||||
import '../theme/app_dimens.dart';
|
||||
|
||||
/// 主题红晕渐变容器:弹框(居中)与底部弹层(半屏)共用的外壳。
|
||||
/// 纯黑弹框统一升级为「顶部红光 → 近黑」的家族渐变。
|
||||
class AppGlowPanel extends StatelessWidget {
|
||||
const AppGlowPanel({
|
||||
super.key,
|
||||
required this.child,
|
||||
this.borderRadius = const BorderRadius.all(Radius.circular(20)),
|
||||
this.border = true,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final BorderRadius borderRadius;
|
||||
final bool border;
|
||||
|
||||
static const _gradient = LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
AppColors.followingGlow,
|
||||
AppColors.followingGlowMid,
|
||||
Color(0xFF101012),
|
||||
],
|
||||
stops: [0, 0.22, 0.62],
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: _gradient,
|
||||
borderRadius: borderRadius,
|
||||
border: border
|
||||
? Border.all(color: AppColors.contentBorder)
|
||||
: null,
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 主题渐变确认弹框:替代 AlertDialog 的家族化外壳。
|
||||
/// 按钮沿用项目惯例:纯文字 TextButton,主操作品牌红。
|
||||
class AppGlowDialog extends StatelessWidget {
|
||||
const AppGlowDialog({
|
||||
super.key,
|
||||
this.title,
|
||||
this.content,
|
||||
this.contentChild,
|
||||
this.actions,
|
||||
this.contentTextStyle,
|
||||
});
|
||||
|
||||
final String? title;
|
||||
final String? content;
|
||||
|
||||
/// 富内容(表单/滚动区),与 [content] 二选一。
|
||||
final Widget? contentChild;
|
||||
final List<Widget>? actions;
|
||||
final TextStyle? contentTextStyle;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bodyStyle = contentTextStyle ??
|
||||
TextStyle(
|
||||
color: AppColors.muted,
|
||||
fontSize: AppDimens.body,
|
||||
fontWeight: FontWeight.w400,
|
||||
);
|
||||
return Dialog(
|
||||
backgroundColor: AppColors.transparent,
|
||||
elevation: 0,
|
||||
child: AppGlowPanel(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(22, 22, 22, 10),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (title != null) ...[
|
||||
Text(
|
||||
title!,
|
||||
style: TextStyle(
|
||||
color: AppColors.onSurface,
|
||||
fontSize: AppDimens.sectionTitle,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
],
|
||||
if (content != null)
|
||||
Text(content!, style: bodyStyle)
|
||||
else if (contentChild != null)
|
||||
// 必须给富内容一个有界高度,否则内部 SingleChildScrollView 拿到无界
|
||||
// 约束会直接撑高整块内容(长文本小屏下溢出且无法滚动)。
|
||||
Flexible(child: contentChild!),
|
||||
if (actions != null && actions!.isNotEmpty) ...[
|
||||
const SizedBox(height: 18),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
for (var i = 0; i < actions!.length; i++) ...[
|
||||
if (i > 0) const SizedBox(width: 4),
|
||||
actions![i],
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../../l10n/app_localizations.dart';
|
||||
import '../../pages/auth/auth_view.dart';
|
||||
import '../data/services/auth_controller.dart';
|
||||
import '../theme/app_colors.dart';
|
||||
import 'app_glow_panel.dart';
|
||||
|
||||
/// 打开登录 / 注册页(沿用现有 Navigator 风格,不引路由库)
|
||||
Future<void> openAuthPage(BuildContext context, {bool signUpMode = false}) {
|
||||
@@ -15,7 +16,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;
|
||||
@@ -23,11 +24,11 @@ Future<bool> ensureSignedIn(BuildContext context) async {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final go = await showModalBottomSheet<bool>(
|
||||
context: context,
|
||||
backgroundColor: AppColors.card,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(18)),
|
||||
),
|
||||
builder: (sheetContext) => SafeArea(
|
||||
backgroundColor: AppColors.transparent,
|
||||
builder: (sheetContext) => AppGlowPanel(
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(18)),
|
||||
border: false,
|
||||
child: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 18, 20, 20),
|
||||
child: Column(
|
||||
@@ -71,11 +72,13 @@ Future<bool> ensureSignedIn(BuildContext context) async {
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (go == true && context.mounted) {
|
||||
await openAuthPage(context);
|
||||
if (context.mounted) return context.read<AuthController>().isSignedIn;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
|
||||
import '../config/app_config.dart';
|
||||
import '../config/server_endpoint.dart';
|
||||
import '../theme/app_colors.dart';
|
||||
import 'app_glow_panel.dart';
|
||||
|
||||
const String _title = '设置服务地址';
|
||||
const String _save = '保存';
|
||||
@@ -72,9 +73,9 @@ class _CatalogEndpointDialogState extends State<_CatalogEndpointDialog> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text(_title),
|
||||
content: SingleChildScrollView(
|
||||
return AppGlowDialog(
|
||||
title: _title,
|
||||
contentChild: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/app_colors.dart';
|
||||
import '../theme/app_dimens.dart';
|
||||
|
||||
class DramaGridSkeleton extends StatelessWidget {
|
||||
const Duration _shimmerPeriod = Duration(milliseconds: 1400);
|
||||
const double _shimmerTravel = 2.4;
|
||||
const double _shimmerStart = -1.2;
|
||||
const double _subtitleWidthFactor = 0.62;
|
||||
const double _shimmerPhaseStep = 0.13;
|
||||
const Color _shimmerHighlight = Color(0x0DFFFFFF);
|
||||
|
||||
/// 首页短剧网格的占位。行数至少铺满可视高度,并带一道扫光。
|
||||
class DramaGridSkeleton extends StatefulWidget {
|
||||
const DramaGridSkeleton({
|
||||
super.key,
|
||||
required this.columns,
|
||||
@@ -23,61 +33,145 @@ class DramaGridSkeleton extends StatelessWidget {
|
||||
final int itemCount;
|
||||
final ScrollPhysics physics;
|
||||
|
||||
@override
|
||||
State<DramaGridSkeleton> createState() => _DramaGridSkeletonState();
|
||||
}
|
||||
|
||||
class _DramaGridSkeletonState extends State<DramaGridSkeleton>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _shimmer = AnimationController(
|
||||
vsync: this,
|
||||
duration: _shimmerPeriod,
|
||||
)..repeat();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_shimmer.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final itemWidth =
|
||||
(constraints.maxWidth -
|
||||
horizontalPadding * 2 -
|
||||
crossAxisSpacing * (columns - 1)) /
|
||||
columns;
|
||||
final itemExtent =
|
||||
itemWidth / AppDimens.cardCoverAspectRatio +
|
||||
AppDimens.skeletonBodyExtent;
|
||||
return GridView.builder(
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
horizontalPadding,
|
||||
AppDimens.spaceMd,
|
||||
horizontalPadding,
|
||||
AppDimens.spaceXl,
|
||||
),
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: columns,
|
||||
crossAxisSpacing: crossAxisSpacing,
|
||||
mainAxisSpacing: mainAxisSpacing,
|
||||
mainAxisExtent: itemExtent,
|
||||
),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => Column(
|
||||
key: Key('drama-grid-skeleton-$index'),
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
AspectRatio(
|
||||
aspectRatio: AppDimens.cardCoverAspectRatio,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.skeletonSurface,
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppDimens.homeCardRadius,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppDimens.cardCoverTitleGap),
|
||||
const _SkeletonBar(),
|
||||
const SizedBox(height: AppDimens.skeletonTitleBarGap),
|
||||
const FractionallySizedBox(
|
||||
widthFactor: 0.62,
|
||||
child: _SkeletonBar(),
|
||||
),
|
||||
],
|
||||
return AnimatedBuilder(
|
||||
animation: _shimmer,
|
||||
builder: (context, _) => _grid(
|
||||
constraints.maxWidth,
|
||||
constraints.maxHeight,
|
||||
_shimmer.value,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _grid(double width, double height, double shimmerValue) {
|
||||
final itemWidth = _itemWidth(width);
|
||||
final itemExtent = _itemExtent(itemWidth);
|
||||
return GridView.builder(
|
||||
physics: widget.physics,
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
widget.horizontalPadding,
|
||||
AppDimens.spaceMd,
|
||||
widget.horizontalPadding,
|
||||
AppDimens.spaceXl,
|
||||
),
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: widget.columns,
|
||||
crossAxisSpacing: widget.crossAxisSpacing,
|
||||
mainAxisSpacing: widget.mainAxisSpacing,
|
||||
mainAxisExtent: itemExtent,
|
||||
),
|
||||
itemCount: _fillCount(height, itemExtent),
|
||||
itemBuilder: (context, index) =>
|
||||
_SkeletonCard(index: index, shimmerValue: shimmerValue),
|
||||
);
|
||||
}
|
||||
|
||||
double _itemWidth(double width) {
|
||||
final gaps = widget.crossAxisSpacing * (widget.columns - 1);
|
||||
return (width - widget.horizontalPadding * 2 - gaps) / widget.columns;
|
||||
}
|
||||
|
||||
double _itemExtent(double itemWidth) {
|
||||
return itemWidth / AppDimens.cardCoverAspectRatio +
|
||||
AppDimens.skeletonBodyExtent;
|
||||
}
|
||||
|
||||
int _fillCount(double height, double extent) {
|
||||
if (!height.isFinite || extent <= 0) return widget.itemCount;
|
||||
final rowHeight = extent + widget.mainAxisSpacing;
|
||||
final rows = (height / rowHeight).ceil() + 1;
|
||||
return math.max(widget.itemCount, rows * widget.columns);
|
||||
}
|
||||
}
|
||||
|
||||
class _SkeletonCard extends StatelessWidget {
|
||||
const _SkeletonCard({required this.index, required this.shimmerValue});
|
||||
|
||||
final int index;
|
||||
final double shimmerValue;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final phase = (shimmerValue + index * _shimmerPhaseStep) % 1.0;
|
||||
return Stack(
|
||||
key: Key('drama-grid-skeleton-$index'),
|
||||
children: [
|
||||
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(),
|
||||
),
|
||||
],
|
||||
),
|
||||
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();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.skeletonSurface,
|
||||
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SkeletonBar extends StatelessWidget {
|
||||
|
||||
@@ -8,19 +8,27 @@ import '../theme/app_colors.dart';
|
||||
import '../theme/app_dimens.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
/// 网络分页列表底部状态:仅保留加载圈与错误重试。
|
||||
/// 网络分页列表底部:加载中、失败重试、没有下一页。
|
||||
class PagedListFooter extends StatelessWidget {
|
||||
const PagedListFooter({
|
||||
super.key,
|
||||
required this.loading,
|
||||
required this.onRetry,
|
||||
this.errorMessage,
|
||||
this.hasMore = true,
|
||||
this.hasItems = false,
|
||||
});
|
||||
|
||||
final bool loading;
|
||||
final String? errorMessage;
|
||||
final Future<void> Function() onRetry;
|
||||
|
||||
/// 还有下一页时不显示结束文案。
|
||||
final bool hasMore;
|
||||
|
||||
/// 列表为空时不显示「没有更多了」。
|
||||
final bool hasItems;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
@@ -58,6 +66,17 @@ class PagedListFooter extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
if (hasItems && !hasMore) {
|
||||
return Padding(
|
||||
key: const Key('paged-list-no-more'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Text(
|
||||
l10n.noMoreItems,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../theme/app_colors.dart';
|
||||
import '../theme/app_dimens.dart';
|
||||
|
||||
@@ -71,10 +72,14 @@ class PagedLoadFooter extends StatelessWidget {
|
||||
super.key,
|
||||
required this.loading,
|
||||
required this.loadMoreKey,
|
||||
this.hasMore = true,
|
||||
this.hasItems = false,
|
||||
});
|
||||
|
||||
final bool loading;
|
||||
final Key loadMoreKey;
|
||||
final bool hasMore;
|
||||
final bool hasItems;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -93,6 +98,18 @@ class PagedLoadFooter extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
if (hasItems && !hasMore) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Padding(
|
||||
key: const Key('paged-list-no-more'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Text(
|
||||
l10n.noMoreItems,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/app_colors.dart';
|
||||
import '../theme/app_theme.dart';
|
||||
import 'subpage_header.dart';
|
||||
|
||||
/// 二级页面通用骨架:返回栏 + 标题/副标题 + 可滚动内容,无底部导航。
|
||||
@@ -29,7 +28,19 @@ class PlainPageScaffold extends StatelessWidget {
|
||||
key: pageKey,
|
||||
backgroundColor: AppColors.ink,
|
||||
body: DecoratedBox(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.pageGradient),
|
||||
// 与首页各 tab 同族:纯黑底 + 顶部暗红光晕。
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
AppColors.followingGlow,
|
||||
AppColors.followingGlowMid,
|
||||
AppColors.appBackground,
|
||||
],
|
||||
stops: [0, 0.14, 0.3],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
|
||||
@@ -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,60 @@ 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);
|
||||
// cover/contain 本身会保持宽高比,此时若同时强制 cacheWidth 和
|
||||
// cacheHeight,解码会把竖版图强行拉成横版像素。只在显式指定了
|
||||
// decodeHeight、或 fit 不保持宽高比时才限定解码高度。
|
||||
final keepsAspectRatio =
|
||||
fit == BoxFit.cover || fit == BoxFit.contain;
|
||||
final cacheHeight = decodeHeight ??
|
||||
(keepsAspectRatio || 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);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const double _height = 52;
|
||||
const double _heightWithSubtitle = 64;
|
||||
const double _horizontal = 14;
|
||||
const double _backSize = 40;
|
||||
const double _backGap = 12;
|
||||
const double _backGap = 6;
|
||||
const double _titleFontSize = 18;
|
||||
const double _subtitleFontSize = 12;
|
||||
const double _actionGap = 8;
|
||||
@@ -163,7 +163,7 @@ class AppSubpageHeader extends StatelessWidget {
|
||||
style: TextStyle(
|
||||
color: foreground,
|
||||
fontSize: _titleFontSize,
|
||||
fontWeight: FontWeight.w800,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
if (subtitle != null) ...[
|
||||
|
||||
+74
-4
@@ -20,7 +20,6 @@
|
||||
"featured": "Featured",
|
||||
"recommended": "Recommended",
|
||||
"fruitShortsBrand": "FruitShorts",
|
||||
"authLandingSubtitle": "Sign in to sync progress, favorites and coins",
|
||||
"comingSoon": "Coming soon",
|
||||
"authLegal": "By continuing, you agree to the Terms of Service and Privacy Policy.",
|
||||
"authLegalLead": "By continuing, you agree to the",
|
||||
@@ -55,12 +54,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",
|
||||
@@ -219,6 +230,7 @@
|
||||
"postComment": "Post",
|
||||
"commentPostSuccess": "Comment posted",
|
||||
"loadMore": "Load more",
|
||||
"noMoreItems": "No more",
|
||||
"commentsLoadFailed": "Comments could not be loaded.",
|
||||
"commentPostFailed": "Could not post your comment.",
|
||||
"delete": "Delete",
|
||||
@@ -262,8 +274,21 @@
|
||||
"shareFailed": "Could not open the share sheet.",
|
||||
"nowPlaying": "Playing now",
|
||||
"pictureInPicture": "Picture in picture",
|
||||
"autoEnterPip": "Auto mini player on exit",
|
||||
"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": {
|
||||
@@ -417,6 +442,7 @@
|
||||
"restoreDefault": "Restore default",
|
||||
"invalidServerAddress": "Enter a valid http(s) server address.",
|
||||
"signOut": "Sign Out",
|
||||
"signOutConfirm": "Sign out of your current account?",
|
||||
"mockUserName": "Vicky sheng",
|
||||
"mockUserId": "ID: M1CZWVYE",
|
||||
"mockNotice": "Sample data only.",
|
||||
@@ -762,8 +788,14 @@
|
||||
"offlineDownloads": "Offline downloads",
|
||||
"watchPreferences": "Watch preferences",
|
||||
"contactSupport": "Contact support",
|
||||
"vipBrandName": "Netshort VIP",
|
||||
"mineVipSubtitle": "Enjoy exclusive benefits",
|
||||
"vipBrandName": "FruitShorts VIP",
|
||||
"vipOpenNow": "Get VIP",
|
||||
"vipBenefitFree": "Free full access",
|
||||
"vipBenefitNoAds": "Ad-free viewing",
|
||||
"vipBenefitHd": "1080P HD",
|
||||
"vipBenefitFastCache": "Fast downloads",
|
||||
"moreServices": "More",
|
||||
"mineVipSubtitle": "Unlock excitement, binge freely",
|
||||
"favoriteEpisodeProgress": "Episode {episode} / {total} total",
|
||||
"@favoriteEpisodeProgress": {
|
||||
"placeholders": {
|
||||
@@ -771,6 +803,44 @@
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"myFavorites": "My Favorites",
|
||||
"manage": "Manage",
|
||||
"continueWatching": "Continue Watching",
|
||||
"continueWatchingSubtitle": "Episode {episode} of {total}",
|
||||
"@continueWatchingSubtitle": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" },
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"favoriteDramas": "Favorites",
|
||||
"totalDramasCount": "{count} titles",
|
||||
"@totalDramasCount": {
|
||||
"placeholders": {
|
||||
"count": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"watchedEpisodeTotal": "EP {episode} / {total}",
|
||||
"@watchedEpisodeTotal": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" },
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"hasUpdateBadge": "UPDATED",
|
||||
"updatedToEpisode": "Updated to EP {episode}",
|
||||
"@updatedToEpisode": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"finishedAllEpisodes": "{total} eps · Completed",
|
||||
"@finishedAllEpisodes": {
|
||||
"placeholders": {
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"noFavoritesYet": "No favorites yet",
|
||||
"watchedToEpisode": "Watched to Episode {episode}",
|
||||
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
|
||||
"homeWatchAll": "Watch all",
|
||||
|
||||
+79
-4
@@ -20,7 +20,6 @@
|
||||
"featured": "Unggulan",
|
||||
"recommended": "Rekomendasi",
|
||||
"fruitShortsBrand": "FruitShorts",
|
||||
"authLandingSubtitle": "Masuk untuk menyinkronkan progres, favorit, dan koin",
|
||||
"comingSoon": "Segera hadir",
|
||||
"authLegal": "Dengan melanjutkan, Anda menyetujui Ketentuan Layanan dan Kebijakan Privasi.",
|
||||
"authLegalLead": "Dengan melanjutkan, Anda menyetujui",
|
||||
@@ -49,7 +48,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",
|
||||
@@ -193,6 +209,7 @@
|
||||
"postComment": "Kirim",
|
||||
"commentPostSuccess": "Komentar terkirim",
|
||||
"loadMore": "Muat lebih banyak",
|
||||
"noMoreItems": "Tidak ada lagi",
|
||||
"commentsLoadFailed": "Komentar tidak dapat dimuat.",
|
||||
"commentPostFailed": "Komentar tidak dapat dikirim.",
|
||||
"delete": "Hapus",
|
||||
@@ -236,8 +253,21 @@
|
||||
"shareFailed": "Tidak bisa membuka menu berbagi.",
|
||||
"nowPlaying": "Sedang diputar",
|
||||
"pictureInPicture": "Gambar dalam gambar",
|
||||
"autoEnterPip": "Mini player otomatis saat keluar",
|
||||
"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": {
|
||||
@@ -391,6 +421,7 @@
|
||||
"restoreDefault": "Pulihkan default",
|
||||
"invalidServerAddress": "Masukkan alamat server http(s) yang valid.",
|
||||
"signOut": "Keluar",
|
||||
"signOutConfirm": "Keluar dari akun saat ini?",
|
||||
"mockUserName": "Vicky sheng",
|
||||
"mockUserId": "ID: M1CZWVYE",
|
||||
"mockNotice": "Hanya data contoh.",
|
||||
@@ -719,8 +750,14 @@
|
||||
"offlineDownloads": "Unduhan offline",
|
||||
"watchPreferences": "Preferensi tontonan",
|
||||
"contactSupport": "Hubungi dukungan",
|
||||
"vipBrandName": "Netshort VIP",
|
||||
"mineVipSubtitle": "Nikmati manfaat eksklusif",
|
||||
"vipBrandName": "FruitShorts VIP",
|
||||
"vipOpenNow": "Buka VIP",
|
||||
"vipBenefitFree": "Nonton semua gratis",
|
||||
"vipBenefitNoAds": "Bebas iklan",
|
||||
"vipBenefitHd": "HD 1080P",
|
||||
"vipBenefitFastCache": "Unduhan cepat",
|
||||
"moreServices": "Lainnya",
|
||||
"mineVipSubtitle": "Buka keseruan, tonton sepuasnya",
|
||||
"favoriteEpisodeProgress": "Episode {episode} / total {total}",
|
||||
"@favoriteEpisodeProgress": {
|
||||
"placeholders": {
|
||||
@@ -728,6 +765,44 @@
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"myFavorites": "Favorit Saya",
|
||||
"manage": "Kelola",
|
||||
"continueWatching": "Lanjutkan",
|
||||
"continueWatchingSubtitle": "Episode {episode} dari {total}",
|
||||
"@continueWatchingSubtitle": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" },
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"favoriteDramas": "Koleksi",
|
||||
"totalDramasCount": "{count} judul",
|
||||
"@totalDramasCount": {
|
||||
"placeholders": {
|
||||
"count": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"watchedEpisodeTotal": "EP {episode} / {total}",
|
||||
"@watchedEpisodeTotal": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" },
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"hasUpdateBadge": "UPDATE",
|
||||
"updatedToEpisode": "Diperbarui ke EP {episode}",
|
||||
"@updatedToEpisode": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"finishedAllEpisodes": "{total} eps · Selesai",
|
||||
"@finishedAllEpisodes": {
|
||||
"placeholders": {
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"noFavoritesYet": "Belum ada favorit",
|
||||
"watchedToEpisode": "Ditonton hingga Episode {episode}",
|
||||
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
|
||||
"homeWatchAll": "Tonton semua",
|
||||
|
||||
+154
-10
@@ -220,12 +220,6 @@ abstract class AppLocalizations {
|
||||
/// **'FruitShorts'**
|
||||
String get fruitShortsBrand;
|
||||
|
||||
/// No description provided for @authLandingSubtitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Sign in to sync progress, favorites and coins'**
|
||||
String get authLandingSubtitle;
|
||||
|
||||
/// No description provided for @comingSoon.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -397,9 +391,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:
|
||||
@@ -994,6 +1000,12 @@ abstract class AppLocalizations {
|
||||
/// **'Load more'**
|
||||
String get loadMore;
|
||||
|
||||
/// No description provided for @noMoreItems.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'No more'**
|
||||
String get noMoreItems;
|
||||
|
||||
/// No description provided for @commentsLoadFailed.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -1180,6 +1192,12 @@ abstract class AppLocalizations {
|
||||
/// **'Picture in picture'**
|
||||
String get pictureInPicture;
|
||||
|
||||
/// No description provided for @autoEnterPip.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Auto mini player on exit'**
|
||||
String get autoEnterPip;
|
||||
|
||||
/// No description provided for @pipUnavailable.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -1192,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:
|
||||
@@ -1780,6 +1828,12 @@ abstract class AppLocalizations {
|
||||
/// **'Sign Out'**
|
||||
String get signOut;
|
||||
|
||||
/// No description provided for @signOutConfirm.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Sign out of your current account?'**
|
||||
String get signOutConfirm;
|
||||
|
||||
/// No description provided for @mockUserName.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -2077,7 +2131,7 @@ abstract class AppLocalizations {
|
||||
/// No description provided for @myFavorites.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'My favorites'**
|
||||
/// **'My Favorites'**
|
||||
String get myFavorites;
|
||||
|
||||
/// No description provided for @noFavorites.
|
||||
@@ -3379,13 +3433,49 @@ abstract class AppLocalizations {
|
||||
/// No description provided for @vipBrandName.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Netshort VIP'**
|
||||
/// **'FruitShorts VIP'**
|
||||
String get vipBrandName;
|
||||
|
||||
/// No description provided for @vipOpenNow.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Get VIP'**
|
||||
String get vipOpenNow;
|
||||
|
||||
/// No description provided for @vipBenefitFree.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Free full access'**
|
||||
String get vipBenefitFree;
|
||||
|
||||
/// No description provided for @vipBenefitNoAds.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Ad-free viewing'**
|
||||
String get vipBenefitNoAds;
|
||||
|
||||
/// No description provided for @vipBenefitHd.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'1080P HD'**
|
||||
String get vipBenefitHd;
|
||||
|
||||
/// No description provided for @vipBenefitFastCache.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Fast downloads'**
|
||||
String get vipBenefitFastCache;
|
||||
|
||||
/// No description provided for @moreServices.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'More'**
|
||||
String get moreServices;
|
||||
|
||||
/// No description provided for @mineVipSubtitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Enjoy exclusive benefits'**
|
||||
/// **'Unlock excitement, binge freely'**
|
||||
String get mineVipSubtitle;
|
||||
|
||||
/// No description provided for @favoriteEpisodeProgress.
|
||||
@@ -3394,6 +3484,60 @@ abstract class AppLocalizations {
|
||||
/// **'Episode {episode} / {total} total'**
|
||||
String favoriteEpisodeProgress(int episode, int total);
|
||||
|
||||
/// No description provided for @manage.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Manage'**
|
||||
String get manage;
|
||||
|
||||
/// No description provided for @continueWatchingSubtitle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Episode {episode} of {total}'**
|
||||
String continueWatchingSubtitle(int episode, int total);
|
||||
|
||||
/// No description provided for @favoriteDramas.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Favorites'**
|
||||
String get favoriteDramas;
|
||||
|
||||
/// No description provided for @totalDramasCount.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{count} titles'**
|
||||
String totalDramasCount(int count);
|
||||
|
||||
/// No description provided for @watchedEpisodeTotal.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'EP {episode} / {total}'**
|
||||
String watchedEpisodeTotal(int episode, int total);
|
||||
|
||||
/// No description provided for @hasUpdateBadge.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'UPDATED'**
|
||||
String get hasUpdateBadge;
|
||||
|
||||
/// No description provided for @updatedToEpisode.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Updated to EP {episode}'**
|
||||
String updatedToEpisode(int episode);
|
||||
|
||||
/// No description provided for @finishedAllEpisodes.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'{total} eps · Completed'**
|
||||
String finishedAllEpisodes(int total);
|
||||
|
||||
/// No description provided for @noFavoritesYet.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'No favorites yet'**
|
||||
String get noFavoritesYet;
|
||||
|
||||
/// No description provided for @watchedToEpisode.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
|
||||
@@ -69,10 +69,6 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get fruitShortsBrand => 'FruitShorts';
|
||||
|
||||
@override
|
||||
String get authLandingSubtitle =>
|
||||
'Sign in to sync progress, favorites and coins';
|
||||
|
||||
@override
|
||||
String get comingSoon => 'Coming soon';
|
||||
|
||||
@@ -162,7 +158,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
|
||||
@@ -486,6 +492,9 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get loadMore => 'Load more';
|
||||
|
||||
@override
|
||||
String get noMoreItems => 'No more';
|
||||
|
||||
@override
|
||||
String get commentsLoadFailed => 'Comments could not be loaded.';
|
||||
|
||||
@@ -584,6 +593,9 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get pictureInPicture => 'Picture in picture';
|
||||
|
||||
@override
|
||||
String get autoEnterPip => 'Auto mini player on exit';
|
||||
|
||||
@override
|
||||
String get pipUnavailable =>
|
||||
'Picture in picture is unavailable on this device';
|
||||
@@ -591,6 +603,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';
|
||||
|
||||
@@ -903,6 +932,9 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get signOut => 'Sign Out';
|
||||
|
||||
@override
|
||||
String get signOutConfirm => 'Sign out of your current account?';
|
||||
|
||||
@override
|
||||
String get mockUserName => 'Vicky sheng';
|
||||
|
||||
@@ -1057,7 +1089,7 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
'Could not update favorites. Please retry.';
|
||||
|
||||
@override
|
||||
String get myFavorites => 'My favorites';
|
||||
String get myFavorites => 'My Favorites';
|
||||
|
||||
@override
|
||||
String get noFavorites => 'No favorites yet.';
|
||||
@@ -1760,16 +1792,71 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
String get contactSupport => 'Contact support';
|
||||
|
||||
@override
|
||||
String get vipBrandName => 'Netshort VIP';
|
||||
String get vipBrandName => 'FruitShorts VIP';
|
||||
|
||||
@override
|
||||
String get mineVipSubtitle => 'Enjoy exclusive benefits';
|
||||
String get vipOpenNow => 'Get VIP';
|
||||
|
||||
@override
|
||||
String get vipBenefitFree => 'Free full access';
|
||||
|
||||
@override
|
||||
String get vipBenefitNoAds => 'Ad-free viewing';
|
||||
|
||||
@override
|
||||
String get vipBenefitHd => '1080P HD';
|
||||
|
||||
@override
|
||||
String get vipBenefitFastCache => 'Fast downloads';
|
||||
|
||||
@override
|
||||
String get moreServices => 'More';
|
||||
|
||||
@override
|
||||
String get mineVipSubtitle => 'Unlock excitement, binge freely';
|
||||
|
||||
@override
|
||||
String favoriteEpisodeProgress(int episode, int total) {
|
||||
return 'Episode $episode / $total total';
|
||||
}
|
||||
|
||||
@override
|
||||
String get manage => 'Manage';
|
||||
|
||||
@override
|
||||
String continueWatchingSubtitle(int episode, int total) {
|
||||
return 'Episode $episode of $total';
|
||||
}
|
||||
|
||||
@override
|
||||
String get favoriteDramas => 'Favorites';
|
||||
|
||||
@override
|
||||
String totalDramasCount(int count) {
|
||||
return '$count titles';
|
||||
}
|
||||
|
||||
@override
|
||||
String watchedEpisodeTotal(int episode, int total) {
|
||||
return 'EP $episode / $total';
|
||||
}
|
||||
|
||||
@override
|
||||
String get hasUpdateBadge => 'UPDATED';
|
||||
|
||||
@override
|
||||
String updatedToEpisode(int episode) {
|
||||
return 'Updated to EP $episode';
|
||||
}
|
||||
|
||||
@override
|
||||
String finishedAllEpisodes(int total) {
|
||||
return '$total eps · Completed';
|
||||
}
|
||||
|
||||
@override
|
||||
String get noFavoritesYet => 'No favorites yet';
|
||||
|
||||
@override
|
||||
String watchedToEpisode(int episode) {
|
||||
return 'Watched to Episode $episode';
|
||||
|
||||
@@ -69,10 +69,6 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get fruitShortsBrand => 'FruitShorts';
|
||||
|
||||
@override
|
||||
String get authLandingSubtitle =>
|
||||
'Masuk untuk menyinkronkan progres, favorit, dan koin';
|
||||
|
||||
@override
|
||||
String get comingSoon => 'Segera hadir';
|
||||
|
||||
@@ -162,7 +158,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
|
||||
@@ -289,7 +295,7 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get localDemoProfile => 'Profil demo lokal';
|
||||
|
||||
@override
|
||||
String get continueWatching => 'Lanjut Tonton';
|
||||
String get continueWatching => 'Lanjutkan';
|
||||
|
||||
@override
|
||||
String episodeRemaining(int episode, int minutes) {
|
||||
@@ -487,6 +493,9 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get loadMore => 'Muat lebih banyak';
|
||||
|
||||
@override
|
||||
String get noMoreItems => 'Tidak ada lagi';
|
||||
|
||||
@override
|
||||
String get commentsLoadFailed => 'Komentar tidak dapat dimuat.';
|
||||
|
||||
@@ -585,6 +594,9 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get pictureInPicture => 'Gambar dalam gambar';
|
||||
|
||||
@override
|
||||
String get autoEnterPip => 'Mini player otomatis saat keluar';
|
||||
|
||||
@override
|
||||
String get pipUnavailable =>
|
||||
'Gambar dalam gambar tidak tersedia di perangkat ini';
|
||||
@@ -592,6 +604,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';
|
||||
|
||||
@@ -907,6 +936,9 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get signOut => 'Keluar';
|
||||
|
||||
@override
|
||||
String get signOutConfirm => 'Keluar dari akun saat ini?';
|
||||
|
||||
@override
|
||||
String get mockUserName => 'Vicky sheng';
|
||||
|
||||
@@ -1059,7 +1091,7 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get favoriteToggleFailed => 'Gagal memperbarui favorit. Coba lagi.';
|
||||
|
||||
@override
|
||||
String get myFavorites => 'Favorit saya';
|
||||
String get myFavorites => 'Favorit Saya';
|
||||
|
||||
@override
|
||||
String get noFavorites => 'Belum ada favorit.';
|
||||
@@ -1762,16 +1794,71 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get contactSupport => 'Hubungi dukungan';
|
||||
|
||||
@override
|
||||
String get vipBrandName => 'Netshort VIP';
|
||||
String get vipBrandName => 'FruitShorts VIP';
|
||||
|
||||
@override
|
||||
String get mineVipSubtitle => 'Nikmati manfaat eksklusif';
|
||||
String get vipOpenNow => 'Buka VIP';
|
||||
|
||||
@override
|
||||
String get vipBenefitFree => 'Nonton semua gratis';
|
||||
|
||||
@override
|
||||
String get vipBenefitNoAds => 'Bebas iklan';
|
||||
|
||||
@override
|
||||
String get vipBenefitHd => 'HD 1080P';
|
||||
|
||||
@override
|
||||
String get vipBenefitFastCache => 'Unduhan cepat';
|
||||
|
||||
@override
|
||||
String get moreServices => 'Lainnya';
|
||||
|
||||
@override
|
||||
String get mineVipSubtitle => 'Buka keseruan, tonton sepuasnya';
|
||||
|
||||
@override
|
||||
String favoriteEpisodeProgress(int episode, int total) {
|
||||
return 'Episode $episode / total $total';
|
||||
}
|
||||
|
||||
@override
|
||||
String get manage => 'Kelola';
|
||||
|
||||
@override
|
||||
String continueWatchingSubtitle(int episode, int total) {
|
||||
return 'Episode $episode dari $total';
|
||||
}
|
||||
|
||||
@override
|
||||
String get favoriteDramas => 'Koleksi';
|
||||
|
||||
@override
|
||||
String totalDramasCount(int count) {
|
||||
return '$count judul';
|
||||
}
|
||||
|
||||
@override
|
||||
String watchedEpisodeTotal(int episode, int total) {
|
||||
return 'EP $episode / $total';
|
||||
}
|
||||
|
||||
@override
|
||||
String get hasUpdateBadge => 'UPDATE';
|
||||
|
||||
@override
|
||||
String updatedToEpisode(int episode) {
|
||||
return 'Diperbarui ke EP $episode';
|
||||
}
|
||||
|
||||
@override
|
||||
String finishedAllEpisodes(int total) {
|
||||
return '$total eps · Selesai';
|
||||
}
|
||||
|
||||
@override
|
||||
String get noFavoritesYet => 'Belum ada favorit';
|
||||
|
||||
@override
|
||||
String watchedToEpisode(int episode) {
|
||||
return 'Ditonton hingga Episode $episode';
|
||||
|
||||
@@ -66,10 +66,7 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
String get recommended => '推荐';
|
||||
|
||||
@override
|
||||
String get fruitShortsBrand => '水果短剧';
|
||||
|
||||
@override
|
||||
String get authLandingSubtitle => '登录后同步进度、收藏与金币权益';
|
||||
String get fruitShortsBrand => 'FruitShorts';
|
||||
|
||||
@override
|
||||
String get comingSoon => '即将上线';
|
||||
@@ -159,7 +156,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
|
||||
@@ -481,6 +488,9 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get loadMore => '加载更多';
|
||||
|
||||
@override
|
||||
String get noMoreItems => '没有更多了';
|
||||
|
||||
@override
|
||||
String get commentsLoadFailed => '评论加载失败,请重试。';
|
||||
|
||||
@@ -578,12 +588,32 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get pictureInPicture => '画中画';
|
||||
|
||||
@override
|
||||
String get autoEnterPip => '退出后自动小窗';
|
||||
|
||||
@override
|
||||
String get pipUnavailable => '此设备无法使用画中画';
|
||||
|
||||
@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 => '短剧';
|
||||
|
||||
@@ -892,6 +922,9 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get signOut => '退出登录';
|
||||
|
||||
@override
|
||||
String get signOutConfirm => '确定要退出当前账号吗?';
|
||||
|
||||
@override
|
||||
String get mockUserName => 'Vicky sheng';
|
||||
|
||||
@@ -1734,16 +1767,71 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
String get contactSupport => '联系客服';
|
||||
|
||||
@override
|
||||
String get vipBrandName => 'Netshort VIP';
|
||||
String get vipBrandName => 'FruitShorts VIP';
|
||||
|
||||
@override
|
||||
String get mineVipSubtitle => '享受专属权益';
|
||||
String get vipOpenNow => '立即开通';
|
||||
|
||||
@override
|
||||
String get vipBenefitFree => '全剧免费看';
|
||||
|
||||
@override
|
||||
String get vipBenefitNoAds => '免广告打扰';
|
||||
|
||||
@override
|
||||
String get vipBenefitHd => '1080P高清';
|
||||
|
||||
@override
|
||||
String get vipBenefitFastCache => '极速缓存';
|
||||
|
||||
@override
|
||||
String get moreServices => '更多服务';
|
||||
|
||||
@override
|
||||
String get mineVipSubtitle => '解锁精彩,畅看好剧';
|
||||
|
||||
@override
|
||||
String favoriteEpisodeProgress(int episode, int total) {
|
||||
return '第 $episode 集 / 共 $total 集';
|
||||
}
|
||||
|
||||
@override
|
||||
String get manage => '管理';
|
||||
|
||||
@override
|
||||
String continueWatchingSubtitle(int episode, int total) {
|
||||
return '看到第 $episode 集 · 全 $total 集';
|
||||
}
|
||||
|
||||
@override
|
||||
String get favoriteDramas => '收藏短剧';
|
||||
|
||||
@override
|
||||
String totalDramasCount(int count) {
|
||||
return '共 $count 部';
|
||||
}
|
||||
|
||||
@override
|
||||
String watchedEpisodeTotal(int episode, int total) {
|
||||
return '看到第 $episode 集 / 全 $total 集';
|
||||
}
|
||||
|
||||
@override
|
||||
String get hasUpdateBadge => '有更新';
|
||||
|
||||
@override
|
||||
String updatedToEpisode(int episode) {
|
||||
return '更新至第 $episode 集';
|
||||
}
|
||||
|
||||
@override
|
||||
String finishedAllEpisodes(int total) {
|
||||
return '全 $total 集 · 已完结';
|
||||
}
|
||||
|
||||
@override
|
||||
String get noFavoritesYet => '还没有收藏的短剧';
|
||||
|
||||
@override
|
||||
String watchedToEpisode(int episode) {
|
||||
return '已看至 第 $episode 集';
|
||||
|
||||
+80
-5
@@ -19,8 +19,7 @@
|
||||
"searchCancel": "取消",
|
||||
"featured": "精选",
|
||||
"recommended": "推荐",
|
||||
"fruitShortsBrand": "水果短剧",
|
||||
"authLandingSubtitle": "登录后同步进度、收藏与金币权益",
|
||||
"fruitShortsBrand": "FruitShorts",
|
||||
"comingSoon": "即将上线",
|
||||
"authLegal": "继续即代表同意《用户协议》与《隐私政策》",
|
||||
"authLegalLead": "继续即代表同意",
|
||||
@@ -49,7 +48,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": "推荐",
|
||||
@@ -193,6 +209,7 @@
|
||||
"postComment": "发布",
|
||||
"commentPostSuccess": "发表成功",
|
||||
"loadMore": "加载更多",
|
||||
"noMoreItems": "没有更多了",
|
||||
"commentsLoadFailed": "评论加载失败,请重试。",
|
||||
"commentPostFailed": "评论发布失败,请重试。",
|
||||
"delete": "删除",
|
||||
@@ -236,8 +253,21 @@
|
||||
"shareFailed": "无法打开系统分享面板。",
|
||||
"nowPlaying": "正在播放",
|
||||
"pictureInPicture": "画中画",
|
||||
"autoEnterPip": "退出后自动小窗",
|
||||
"pipUnavailable": "此设备无法使用画中画",
|
||||
"originalTag": "原创",
|
||||
"originalProduction": "原创出品",
|
||||
"watchNowAction": "立即观看",
|
||||
"newArrivalBadge": "上新",
|
||||
"editorPick": "编辑精选",
|
||||
"totalEpisodesShort": "全{count}集",
|
||||
"@totalEpisodesShort": {
|
||||
"placeholders": {
|
||||
"count": {
|
||||
"type": "int"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dramaTag": "短剧",
|
||||
"episodeLabel": "第 {number} 集",
|
||||
"@episodeLabel": {
|
||||
@@ -353,6 +383,7 @@
|
||||
"restoreDefault": "恢复默认",
|
||||
"invalidServerAddress": "请输入有效的 http(s) 服务器地址。",
|
||||
"signOut": "退出登录",
|
||||
"signOutConfirm": "确定要退出当前账号吗?",
|
||||
"mockUserName": "Vicky sheng",
|
||||
"mockUserId": "ID: M1CZWVYE",
|
||||
"mockNotice": "当前是示例数据。",
|
||||
@@ -681,8 +712,14 @@
|
||||
"offlineDownloads": "离线缓存",
|
||||
"watchPreferences": "观看偏好",
|
||||
"contactSupport": "联系客服",
|
||||
"vipBrandName": "Netshort VIP",
|
||||
"mineVipSubtitle": "享受专属权益",
|
||||
"vipBrandName": "FruitShorts VIP",
|
||||
"vipOpenNow": "立即开通",
|
||||
"vipBenefitFree": "全剧免费看",
|
||||
"vipBenefitNoAds": "免广告打扰",
|
||||
"vipBenefitHd": "1080P高清",
|
||||
"vipBenefitFastCache": "极速缓存",
|
||||
"moreServices": "更多服务",
|
||||
"mineVipSubtitle": "解锁精彩,畅看好剧",
|
||||
"favoriteEpisodeProgress": "第 {episode} 集 / 共 {total} 集",
|
||||
"@favoriteEpisodeProgress": {
|
||||
"placeholders": {
|
||||
@@ -690,6 +727,44 @@
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"myFavorites": "我的收藏",
|
||||
"manage": "管理",
|
||||
"continueWatching": "继续观看",
|
||||
"continueWatchingSubtitle": "看到第 {episode} 集 · 全 {total} 集",
|
||||
"@continueWatchingSubtitle": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" },
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"favoriteDramas": "收藏短剧",
|
||||
"totalDramasCount": "共 {count} 部",
|
||||
"@totalDramasCount": {
|
||||
"placeholders": {
|
||||
"count": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"watchedEpisodeTotal": "看到第 {episode} 集 / 全 {total} 集",
|
||||
"@watchedEpisodeTotal": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" },
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"hasUpdateBadge": "有更新",
|
||||
"updatedToEpisode": "更新至第 {episode} 集",
|
||||
"@updatedToEpisode": {
|
||||
"placeholders": {
|
||||
"episode": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"finishedAllEpisodes": "全 {total} 集 · 已完结",
|
||||
"@finishedAllEpisodes": {
|
||||
"placeholders": {
|
||||
"total": { "type": "int" }
|
||||
}
|
||||
},
|
||||
"noFavoritesYet": "还没有收藏的短剧",
|
||||
"watchedToEpisode": "已看至 第 {episode} 集",
|
||||
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
|
||||
"homeWatchAll": "观看全集",
|
||||
|
||||
+5
-1
@@ -2,17 +2,21 @@
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'app.dart';
|
||||
import 'core/config/app_config.dart';
|
||||
import 'core/config/server_endpoint.dart';
|
||||
import 'core/platform/wireless_data_prompt.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await ServerEndpoint.load();
|
||||
AppConfig.ready = AppConfig.probeAndApplyBaseUrl();
|
||||
AppConfig.ready = WirelessDataPrompt.awaitDecision(
|
||||
enabled: !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS,
|
||||
).then((_) => AppConfig.probeAndApplyBaseUrl());
|
||||
runApp(const LumaDramaApp());
|
||||
unawaited(
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
|
||||
|
||||
@@ -11,6 +11,7 @@ import '../../core/formatting/localized_date_time.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
import '../../core/theme/app_dimens.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../core/widgets/app_glow_panel.dart';
|
||||
import '../../core/widgets/auth_gate.dart';
|
||||
import '../../core/widgets/plain_page_scaffold.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
@@ -119,7 +120,10 @@ class _AccountDeactivatePageState extends State<AccountDeactivatePage> {
|
||||
controller: _reason,
|
||||
maxLength: AccountDeactivateLogic.maxReasonLength,
|
||||
maxLines: 4,
|
||||
textAlignVertical: TextAlignVertical.top,
|
||||
decoration: InputDecoration(
|
||||
alignLabelWithHint: true,
|
||||
floatingLabelBehavior: FloatingLabelBehavior.auto,
|
||||
labelText: l10n.accountDeactivateReason,
|
||||
hintText: l10n.accountDeactivateReasonHint,
|
||||
),
|
||||
@@ -169,15 +173,15 @@ class _AccountDeactivatePageState extends State<AccountDeactivatePage> {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.accountConfirmDeactivateTitle),
|
||||
content: Text(l10n.accountConfirmDeactivateMessage),
|
||||
builder: (dialogContext) => AppGlowDialog(
|
||||
title: l10n.accountConfirmDeactivateTitle,
|
||||
content: l10n.accountConfirmDeactivateMessage,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
TextButton(
|
||||
key: const Key('account-deactivate-confirm'),
|
||||
onPressed: () => Navigator.of(dialogContext).pop(true),
|
||||
child: Text(l10n.accountConfirmDeactivate),
|
||||
|
||||
@@ -45,8 +45,7 @@ class AccountEntryCard extends StatelessWidget {
|
||||
];
|
||||
return Material(
|
||||
key: const Key('mine-account-card'),
|
||||
color: AppColors.card,
|
||||
borderRadius: BorderRadius.circular(AppDimens.cardRadius),
|
||||
color: AppColors.contentSurface,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Column(
|
||||
children: [
|
||||
@@ -55,7 +54,7 @@ class AccountEntryCard extends StatelessWidget {
|
||||
const Divider(
|
||||
height: AppDimens.mineGridDividerWidth,
|
||||
thickness: AppDimens.mineGridDividerWidth,
|
||||
color: AppColors.outlineVariantDark,
|
||||
color: AppColors.contentBorder,
|
||||
),
|
||||
_AccountListTile(row: rows[index]),
|
||||
],
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
|
||||
@@ -61,7 +61,7 @@ class _AuthFields extends StatelessWidget {
|
||||
onChanged: callbacks.onEmailChanged,
|
||||
onSubmitted: (_) => state.fields.passwordFocus.requestFocus(),
|
||||
style: const TextStyle(color: AppColors.onSurface, fontSize: 15),
|
||||
cursorColor: AppColors.blue,
|
||||
cursorColor: AppColors.brandRed,
|
||||
decoration: _decoration(
|
||||
context: context,
|
||||
hint: 'name@example.com',
|
||||
@@ -93,7 +93,7 @@ class _AuthFields extends StatelessWidget {
|
||||
onChanged: callbacks.onPasswordChanged,
|
||||
onSubmitted: (_) => callbacks.onSubmit(),
|
||||
style: const TextStyle(color: AppColors.onSurface, fontSize: 15),
|
||||
cursorColor: AppColors.blue,
|
||||
cursorColor: AppColors.brandRed,
|
||||
decoration: _decoration(
|
||||
context: context,
|
||||
hint: l10n.authPasswordHint,
|
||||
@@ -128,7 +128,7 @@ class _AuthFields extends StatelessWidget {
|
||||
style: const TextStyle(
|
||||
color: AppColors.muted,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -142,10 +142,7 @@ class _AuthFields extends StatelessWidget {
|
||||
}) {
|
||||
final border = OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(_fieldRadius),
|
||||
borderSide: const BorderSide(
|
||||
color: AppColors.border,
|
||||
width: _fieldBorderWidth,
|
||||
),
|
||||
borderSide: BorderSide.none,
|
||||
);
|
||||
final errorColor = Theme.of(context).colorScheme.error;
|
||||
final errorBorder = OutlineInputBorder(
|
||||
@@ -158,7 +155,7 @@ class _AuthFields extends StatelessWidget {
|
||||
prefixIcon: Icon(
|
||||
icon,
|
||||
size: 21,
|
||||
color: focused ? AppColors.blue : AppColors.muted,
|
||||
color: focused ? AppColors.brandRed : AppColors.muted,
|
||||
),
|
||||
prefixIconConstraints: const BoxConstraints(
|
||||
minWidth: _minTapTarget,
|
||||
@@ -166,7 +163,7 @@ class _AuthFields extends StatelessWidget {
|
||||
),
|
||||
suffixIcon: suffix,
|
||||
filled: true,
|
||||
fillColor: AppColors.card,
|
||||
fillColor: Colors.white.withValues(alpha: 0.05),
|
||||
isDense: true,
|
||||
contentPadding: const EdgeInsets.only(right: 16),
|
||||
border: border,
|
||||
@@ -175,7 +172,7 @@ class _AuthFields extends StatelessWidget {
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(_fieldRadius),
|
||||
borderSide: const BorderSide(
|
||||
color: AppColors.blue,
|
||||
color: AppColors.brandRed,
|
||||
width: _fieldBorderWidth,
|
||||
),
|
||||
),
|
||||
@@ -204,17 +201,17 @@ class _AuthSubmitButton extends StatelessWidget {
|
||||
style: ButtonStyle(
|
||||
backgroundColor: WidgetStateProperty.resolveWith((states) {
|
||||
if (states.contains(WidgetState.disabled)) {
|
||||
return AppColors.blue.withValues(alpha: 0.5);
|
||||
return AppColors.brandRed.withValues(alpha: 0.5);
|
||||
}
|
||||
if (states.contains(WidgetState.pressed)) {
|
||||
return AppColors.bluePressed;
|
||||
return AppColors.brandRedPressed;
|
||||
}
|
||||
return AppColors.blue;
|
||||
return AppColors.brandRed;
|
||||
}),
|
||||
foregroundColor: const WidgetStatePropertyAll(AppColors.onPrimary),
|
||||
elevation: const WidgetStatePropertyAll(2),
|
||||
shadowColor: WidgetStatePropertyAll(
|
||||
AppColors.blue.withValues(alpha: 0.22),
|
||||
AppColors.brandRed.withValues(alpha: 0.22),
|
||||
),
|
||||
padding: const WidgetStatePropertyAll(EdgeInsets.zero),
|
||||
shape: WidgetStatePropertyAll(
|
||||
@@ -235,7 +232,7 @@ class _AuthSubmitButton extends StatelessWidget {
|
||||
status.signUpMode ? l10n.signUp : l10n.signIn,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w800,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -243,18 +240,16 @@ class _AuthSubmitButton extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _ModeSegment extends StatelessWidget {
|
||||
const _ModeSegment({
|
||||
class _ModeTab extends StatelessWidget {
|
||||
const _ModeTab({
|
||||
required this.segmentKey,
|
||||
required this.label,
|
||||
required this.hiddenLabel,
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final Key segmentKey;
|
||||
final String label;
|
||||
final String hiddenLabel;
|
||||
final bool selected;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
@@ -264,38 +259,29 @@ class _ModeSegment extends StatelessWidget {
|
||||
key: segmentKey,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onTap,
|
||||
child: AnimatedContainer(
|
||||
duration: _segmentDuration,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: selected ? AppColors.blue : AppColors.transparent,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
// 文字 + 指示条只有约 32px 高,补上下各 6px 把可点区域撑到 44。
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Center(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: selected ? AppColors.onPrimary : AppColors.onSurface,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: selected ? AppColors.textPrimary : AppColors.muted,
|
||||
fontSize: AppDimens.followingSegmentFont,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
Positioned.fill(
|
||||
child: ExcludeSemantics(
|
||||
child: Opacity(
|
||||
opacity: 0,
|
||||
child: Center(
|
||||
child: Text(
|
||||
hiddenLabel,
|
||||
maxLines: 1,
|
||||
softWrap: false,
|
||||
style: const TextStyle(fontSize: 14),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppDimens.followingSegmentIndicatorTopGap),
|
||||
Container(
|
||||
width: AppDimens.followingSegmentIndicatorWidth,
|
||||
height: AppDimens.followingSegmentIndicatorHeight,
|
||||
decoration: BoxDecoration(
|
||||
color: selected ? AppColors.brandRed : AppColors.transparent,
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppDimens.followingSegmentIndicatorRadius,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -349,7 +335,7 @@ class _AuthBrand extends StatelessWidget {
|
||||
style: const TextStyle(
|
||||
color: AppColors.onSurface,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w900,
|
||||
fontWeight: FontWeight.w700,
|
||||
height: 1.1,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -50,7 +50,7 @@ class _AuthLegalLinksState extends State<AuthLegalLinks> {
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final muted = TextStyle(color: AppColors.muted, fontSize: _legalFontSize, height: 1.6);
|
||||
final link = muted.copyWith(color: AppColors.blue);
|
||||
final link = muted.copyWith(color: AppColors.brandRed);
|
||||
return Text.rich(
|
||||
TextSpan(
|
||||
style: muted,
|
||||
|
||||
@@ -24,18 +24,14 @@ part 'auth_widgets.dart';
|
||||
part 'auth_form_widgets.dart';
|
||||
|
||||
const double _minTapTarget = 44;
|
||||
const double _brandMarkSize = 72;
|
||||
const double _brandMarkSize = 88;
|
||||
const double _compactBrandMarkSize = 48;
|
||||
const double _brandMarkRadius = 20;
|
||||
const double _brandMarkRadius = 26;
|
||||
const double _compactBrandMarkRadius = 14;
|
||||
const double _landingLogoTopGap = 28;
|
||||
const String _appLogoAsset = 'assets/icon/fruitshorts.png';
|
||||
const double _contentMaxWidth = 440;
|
||||
// Auth keeps its approved 20px card silhouette.
|
||||
const double _cardRadius = AppDimens.authCardRadius;
|
||||
const double _cardPadding = 20;
|
||||
const double _fieldHeight = 52;
|
||||
const double _fieldRadius = 14;
|
||||
const double _fieldRadius = 12;
|
||||
const double _fieldBorderWidth = 1;
|
||||
const double _buttonHeight = 50;
|
||||
const double _buttonRadius = 25;
|
||||
@@ -47,14 +43,11 @@ const double _bottomContentPadding = 28;
|
||||
const double _compactTopContentPadding = 40;
|
||||
const double _compactHeightBreakpoint = 720;
|
||||
const double _compactBrandGap = 16;
|
||||
const double _glowSize = 280;
|
||||
const double _warmGlowOpacity = 0.18;
|
||||
const double _entryButtonHeight = 50;
|
||||
const double _entryButtonRadius = 25;
|
||||
const double _entryButtonHeight = 52;
|
||||
const double _entryButtonRadius = 26;
|
||||
const double _entryButtonFontSize = 15;
|
||||
const double _entryIconSize = 20;
|
||||
const Duration _enterDuration = Duration(milliseconds: 220);
|
||||
const Duration _segmentDuration = Duration(milliseconds: 160);
|
||||
|
||||
Widget _brandMarkWidget({
|
||||
Key? key,
|
||||
@@ -267,45 +260,53 @@ class _AuthPageState extends State<AuthPage> {
|
||||
child: IgnorePointer(
|
||||
child: DecoratedBox(
|
||||
key: Key('auth-page-background'),
|
||||
decoration: BoxDecoration(gradient: AppTheme.pageGradient),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: -90,
|
||||
right: -70,
|
||||
width: _glowSize,
|
||||
height: _glowSize,
|
||||
child: IgnorePointer(
|
||||
child: Container(
|
||||
key: const Key('auth-background-glow'),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
gradient: RadialGradient(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
AppColors.surfaceTop,
|
||||
AppColors.surfaceTop.withValues(alpha: 0),
|
||||
AppColors.followingGlow,
|
||||
AppColors.followingGlowMid,
|
||||
AppColors.appBackground,
|
||||
],
|
||||
stops: [0, 0.14, 0.3],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: -110,
|
||||
bottom: -90,
|
||||
width: _glowSize,
|
||||
height: _glowSize,
|
||||
// 全屏海报背景:压暗保证文字可读,顶部再叠品牌红光。
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(child: _AuthPosterBackdrop()),
|
||||
),
|
||||
const Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: Container(
|
||||
key: const Key('auth-background-warm-glow'),
|
||||
child: DecoratedBox(
|
||||
key: Key('auth-poster-scrim'),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
gradient: RadialGradient(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
AppColors.gold.withValues(alpha: _warmGlowOpacity),
|
||||
AppColors.gold.withValues(alpha: 0),
|
||||
Color(0x66000000),
|
||||
Color(0x14000000),
|
||||
Color(0xE0000000),
|
||||
],
|
||||
stops: [0, 0.42, 1],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: DecoratedBox(
|
||||
key: Key('auth-red-glow'),
|
||||
decoration: BoxDecoration(
|
||||
gradient: RadialGradient(
|
||||
center: Alignment(0, -1.15),
|
||||
radius: 1.3,
|
||||
colors: [AppColors.primaryBorder, AppColors.transparent],
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -347,7 +348,11 @@ class _AuthPageState extends State<AuthPage> {
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: _contentMaxWidth,
|
||||
),
|
||||
child: _content(l10n, compact: compact),
|
||||
child: _content(
|
||||
l10n,
|
||||
compact: compact,
|
||||
minHeight: minHeight,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -387,7 +392,11 @@ class _AuthPageState extends State<AuthPage> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _content(AppLocalizations l10n, {required bool compact}) =>
|
||||
Widget _content(
|
||||
AppLocalizations l10n, {
|
||||
required bool compact,
|
||||
required double minHeight,
|
||||
}) =>
|
||||
TweenAnimationBuilder<double>(
|
||||
key: const Key('auth-enter-animation'),
|
||||
tween: Tween(begin: 0, end: 1),
|
||||
@@ -409,15 +418,18 @@ class _AuthPageState extends State<AuthPage> {
|
||||
_authCard(l10n),
|
||||
],
|
||||
)
|
||||
: _landing(l10n),
|
||||
: _landing(l10n, minHeight: minHeight),
|
||||
);
|
||||
|
||||
Widget _landing(AppLocalizations l10n) => Column(
|
||||
/// 落地页内容需要有限高度才能用 Spacer 三段分割,这里显式钉住可用高度。
|
||||
Widget _landing(AppLocalizations l10n, {required double minHeight}) =>
|
||||
SizedBox(
|
||||
height: minHeight,
|
||||
child: Column(
|
||||
key: const Key('auth-landing'),
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: _landingLogoTopGap),
|
||||
const Spacer(flex: 5),
|
||||
Center(
|
||||
child: _brandMarkWidget(
|
||||
key: const Key('auth-brand-logo'),
|
||||
@@ -425,24 +437,19 @@ class _AuthPageState extends State<AuthPage> {
|
||||
radius: _brandMarkRadius,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
l10n.fruitShortsBrand,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
fontFamily: 'Outfit',
|
||||
color: AppColors.onSurface,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w900,
|
||||
fontSize: 26,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 2,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
l10n.authLandingSubtitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.muted, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
const Spacer(flex: 3),
|
||||
_AuthEntryButton(
|
||||
key: const Key('auth-entry-phone'),
|
||||
label: l10n.authPhoneSignIn,
|
||||
@@ -458,10 +465,12 @@ class _AuthPageState extends State<AuthPage> {
|
||||
primary: false,
|
||||
onTap: () => setState(() => _emailEntryOpen = true),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
const AuthLegalLinks(),
|
||||
],
|
||||
);
|
||||
const SizedBox(height: 14),
|
||||
const Opacity(opacity: 0.75, child: AuthLegalLinks()),
|
||||
const Spacer(flex: 6),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> _openPhoneSheet() async {
|
||||
final signedIn = await showPhoneAuthSheet(
|
||||
@@ -526,15 +535,15 @@ class _AuthEntryButton extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final background = primary ? AppColors.blue : AppColors.card;
|
||||
// 主按钮纯品牌红;次按钮为无边框深色玻璃(白 6%),Apple 风格。
|
||||
final background = primary
|
||||
? AppColors.brandRed
|
||||
: Colors.white.withValues(alpha: 0.06);
|
||||
final foreground = primary ? AppColors.onPrimary : AppColors.onSurface;
|
||||
return Material(
|
||||
color: background,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(_entryButtonRadius),
|
||||
side: primary
|
||||
? BorderSide.none
|
||||
: const BorderSide(color: AppColors.border),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
@@ -556,7 +565,7 @@ class _AuthEntryButton extends StatelessWidget {
|
||||
style: TextStyle(
|
||||
color: foreground,
|
||||
fontSize: _entryButtonFontSize,
|
||||
fontWeight: FontWeight.w800,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -567,3 +576,18 @@ class _AuthEntryButton extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 登录页全屏海报背景(单张,无拼缝)。
|
||||
class _AuthPosterBackdrop extends StatelessWidget {
|
||||
const _AuthPosterBackdrop();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Image.asset(
|
||||
key: const Key('auth-poster-backdrop'),
|
||||
'assets/auth/bg_3.jpg',
|
||||
fit: BoxFit.cover,
|
||||
alignment: Alignment.center,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -70,52 +70,45 @@ class _AuthCard extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = state.l10n;
|
||||
final status = state.status;
|
||||
return Container(
|
||||
// 不再做卡片盒子,表单直接排在红光晕背景上。
|
||||
return Column(
|
||||
key: const Key('auth-card'),
|
||||
padding: const EdgeInsets.all(_cardPadding),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.card,
|
||||
borderRadius: BorderRadius.circular(_cardRadius),
|
||||
border: Border.all(color: AppColors.border),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_AuthModeSwitch(
|
||||
l10n: l10n,
|
||||
signUpMode: status.signUpMode,
|
||||
busy: status.busy,
|
||||
onSelected: callbacks.onModeSelected,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_AuthModeSwitch(
|
||||
l10n: l10n,
|
||||
signUpMode: status.signUpMode,
|
||||
busy: status.busy,
|
||||
onSelected: callbacks.onModeSelected,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
status.signUpMode ? l10n.authSignUpTitle : l10n.authSignInTitle,
|
||||
style: const TextStyle(
|
||||
color: AppColors.onSurface,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w600,
|
||||
height: 1.2,
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
Text(
|
||||
status.signUpMode ? l10n.authSignUpTitle : l10n.authSignInTitle,
|
||||
style: const TextStyle(
|
||||
color: AppColors.onSurface,
|
||||
fontSize: 25,
|
||||
fontWeight: FontWeight.w800,
|
||||
height: 1.2,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
status.signUpMode ? l10n.authSignUpSubtitle : l10n.authSubtitle,
|
||||
style: const TextStyle(
|
||||
color: AppColors.muted,
|
||||
fontSize: AppDimens.body,
|
||||
height: 1.45,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
status.signUpMode ? l10n.authSignUpSubtitle : l10n.authSubtitle,
|
||||
style: const TextStyle(
|
||||
color: AppColors.muted,
|
||||
fontSize: AppDimens.body,
|
||||
height: 1.45,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
_AuthFields(state: state, callbacks: callbacks),
|
||||
if (status.errorMessage != null) ...[
|
||||
const SizedBox(height: 14),
|
||||
_AuthError(message: status.errorMessage!),
|
||||
],
|
||||
const SizedBox(height: 22),
|
||||
_AuthSubmitButton(state: state, onSubmit: callbacks.onSubmit),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_AuthFields(state: state, callbacks: callbacks),
|
||||
if (status.errorMessage != null) ...[
|
||||
const SizedBox(height: 14),
|
||||
_AuthError(message: status.errorMessage!),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
_AuthSubmitButton(state: state, onSubmit: callbacks.onSubmit),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -135,47 +128,23 @@ class _AuthModeSwitch extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextButton(
|
||||
return Row(
|
||||
key: const Key('auth-switch-mode'),
|
||||
onPressed: busy ? null : () => onSelected(!signUpMode),
|
||||
style: TextButton.styleFrom(
|
||||
minimumSize: const Size(0, _minTapTarget),
|
||||
padding: EdgeInsets.zero,
|
||||
overlayColor: AppColors.transparent,
|
||||
splashFactory: NoSplash.splashFactory,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
|
||||
),
|
||||
child: Container(
|
||||
height: 36,
|
||||
padding: const EdgeInsets.all(2),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.raised,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
children: [
|
||||
_ModeTab(
|
||||
segmentKey: const Key('auth-mode-sign-in'),
|
||||
label: l10n.signIn,
|
||||
selected: !signUpMode,
|
||||
onTap: busy ? null : () => onSelected(false),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _ModeSegment(
|
||||
segmentKey: const Key('auth-mode-sign-in'),
|
||||
label: l10n.signIn,
|
||||
hiddenLabel: l10n.authSwitchToSignIn,
|
||||
selected: !signUpMode,
|
||||
onTap: busy ? null : () => onSelected(false),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: _ModeSegment(
|
||||
segmentKey: const Key('auth-mode-sign-up'),
|
||||
label: l10n.signUp,
|
||||
hiddenLabel: l10n.authSwitchToSignUp,
|
||||
selected: signUpMode,
|
||||
onTap: busy ? null : () => onSelected(true),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(width: AppDimens.followingSegmentGap),
|
||||
_ModeTab(
|
||||
segmentKey: const Key('auth-mode-sign-up'),
|
||||
label: l10n.signUp,
|
||||
selected: signUpMode,
|
||||
onTap: busy ? null : () => onSelected(true),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,10 @@ 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';
|
||||
import '../../core/widgets/app_glow_panel.dart';
|
||||
import '../../core/widgets/centered_toast.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
@@ -181,7 +181,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
||||
).showSnackBar(SnackBar(content: Text(l10n.authCodeSent)));
|
||||
_codeFocus.requestFocus();
|
||||
} on ApiException catch (error) {
|
||||
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
|
||||
failureMessage = error.message;
|
||||
} catch (_) {
|
||||
failureMessage = l10n.authNetworkError;
|
||||
} finally {
|
||||
@@ -229,7 +229,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
||||
}
|
||||
if (mounted) Navigator.of(context).pop(true);
|
||||
} on ApiException catch (error) {
|
||||
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
|
||||
failureMessage = error.message;
|
||||
} catch (_) {
|
||||
failureMessage = l10n.authNetworkError;
|
||||
} finally {
|
||||
@@ -253,15 +253,15 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
||||
final bottom = effectiveKeyboardInset(context, _keyboardInset);
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(bottom: bottom),
|
||||
child: Container(
|
||||
key: const Key('phone-auth-sheet'),
|
||||
decoration: const BoxDecoration(
|
||||
color: AppColors.card,
|
||||
borderRadius: BorderRadius.vertical(
|
||||
top: Radius.circular(_sheetRadius),
|
||||
),
|
||||
child: AppGlowPanel(
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(_sheetRadius),
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
border: false,
|
||||
child: Container(
|
||||
key: const Key('phone-auth-sheet'),
|
||||
decoration: const BoxDecoration(color: AppColors.transparent),
|
||||
child: SingleChildScrollView(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.fromLTRB(22, 10, 22, 26),
|
||||
child: Column(
|
||||
@@ -314,6 +314,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -404,7 +405,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
||||
key: const Key('auth-phone-submit'),
|
||||
onPressed: _submitting ? null : _submit,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: AppColors.blue,
|
||||
backgroundColor: AppColors.brandRed,
|
||||
foregroundColor: AppColors.onPrimary,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(_buttonHeight / 2),
|
||||
@@ -440,7 +441,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(_fieldRadius),
|
||||
borderSide: const BorderSide(color: AppColors.blue, width: 1.5),
|
||||
borderSide: const BorderSide(color: AppColors.brandRed, width: 1.5),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -23,30 +23,18 @@ import '../../core/widgets/catalog_debug_info.dart';
|
||||
import '../../core/widgets/catalog_endpoint_editor.dart';
|
||||
import '../../core/widgets/empty_state.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../filter/filter_page.dart';
|
||||
import '../new_releases/new_releases_page.dart';
|
||||
import '../player/open_player.dart';
|
||||
import '../ranking/ranking_page.dart';
|
||||
import '../reserve/reserve_page.dart';
|
||||
import 'discover_binding.dart';
|
||||
import 'discover_logic.dart';
|
||||
import 'discover_types.dart';
|
||||
import 'widgets/discover_category_tab.dart';
|
||||
import 'widgets/discover_header.dart';
|
||||
import 'widgets/discover_search_results.dart';
|
||||
import 'widgets/discover_toolbar.dart';
|
||||
import 'widgets/drama_grid.dart';
|
||||
|
||||
const Color _filterIconColor = AppColors.blueSoft;
|
||||
const Color _newIconColor = AppColors.blueSoft;
|
||||
const double _toolbarHeight = 36;
|
||||
const double _toolbarGap = 10;
|
||||
const double _toolbarRadius = 10;
|
||||
const double _categoryTabHeight = 44;
|
||||
const double _categoryTabGap = 20;
|
||||
const double _categorySelectedFontSize = 16;
|
||||
const double _categoryFontSize = 15;
|
||||
const double _categoryUnderlineWidth = 20;
|
||||
const double _categoryUnderlineHeight = 3;
|
||||
const double _categoryUnderlineStrokeWidth = 2;
|
||||
const double _stickyHeaderHeight = 44;
|
||||
const Duration _stickyHeaderTransition = Duration(milliseconds: 160);
|
||||
const Duration _categoryScrollDuration = Duration(milliseconds: 200);
|
||||
@@ -295,7 +283,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
List<Widget> _theaterBlocks(AppLocalizations l10n) {
|
||||
final dramas = theater.dramas;
|
||||
return [
|
||||
_toolbar(l10n),
|
||||
_toolbar(),
|
||||
if (dramas.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 40),
|
||||
@@ -318,6 +306,16 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (dramas.isNotEmpty && !theater.hasMore)
|
||||
Padding(
|
||||
key: const Key('paged-list-no-more'),
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Text(
|
||||
l10n.noMoreItems,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -335,8 +333,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_categoryTab(
|
||||
key: const Key('theater-category-all'),
|
||||
DiscoverCategoryTab(
|
||||
anchorKey: _anchorFor('all'),
|
||||
id: 'all',
|
||||
label: l10n.all,
|
||||
@@ -345,8 +342,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
),
|
||||
for (final category in categories.categories) ...[
|
||||
const SizedBox(width: _categoryTabGap),
|
||||
_categoryTab(
|
||||
key: Key('theater-category-${category.id}'),
|
||||
DiscoverCategoryTab(
|
||||
anchorKey: _anchorFor(category.id),
|
||||
id: category.id,
|
||||
label: category.name,
|
||||
@@ -360,52 +356,6 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _categoryTab({
|
||||
required Key key,
|
||||
required GlobalKey anchorKey,
|
||||
required String id,
|
||||
required String label,
|
||||
required bool selected,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return KeyedSubtree(
|
||||
key: anchorKey,
|
||||
child: GestureDetector(
|
||||
key: key,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onTap,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
style: TextStyle(
|
||||
color: selected ? AppColors.onSurface : AppColors.muted,
|
||||
fontSize: selected
|
||||
? _categorySelectedFontSize
|
||||
: _categoryFontSize,
|
||||
fontWeight: selected ? FontWeight.w800 : FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
CustomPaint(
|
||||
key: Key('theater-category-underline-$id'),
|
||||
size: const Size(
|
||||
_categoryUnderlineWidth,
|
||||
_categoryUnderlineHeight,
|
||||
),
|
||||
painter: CategoryUnderlinePainter(
|
||||
color: selected ? AppColors.blue : AppColors.transparent,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
GlobalKey _anchorFor(String id) {
|
||||
return _categoryAnchors.putIfAbsent(id, GlobalKey.new);
|
||||
}
|
||||
@@ -444,97 +394,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
return true;
|
||||
}
|
||||
|
||||
Widget _toolbar(AppLocalizations l10n) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 2, 14, 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _toolButton(
|
||||
key: const Key('theater-toolbar-filter'),
|
||||
icon: Icons.tune_rounded,
|
||||
color: _filterIconColor,
|
||||
label: l10n.filter,
|
||||
onTap: () => _openPage(context, const FilterPage()),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _toolbarGap),
|
||||
Expanded(
|
||||
child: _toolButton(
|
||||
key: const Key('theater-toolbar-ranking'),
|
||||
icon: Icons.local_fire_department_rounded,
|
||||
color: AppColors.blue,
|
||||
label: l10n.rankingTab,
|
||||
onTap: () => _openPage(context, const RankingPage()),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _toolbarGap),
|
||||
Expanded(
|
||||
child: _toolButton(
|
||||
key: const Key('theater-toolbar-new'),
|
||||
icon: Icons.play_circle_fill_rounded,
|
||||
color: _newIconColor,
|
||||
label: l10n.newDramas,
|
||||
onTap: () => _openPage(context, const NewReleasesPage()),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _toolbarGap),
|
||||
Expanded(
|
||||
child: _toolButton(
|
||||
key: const Key('theater-toolbar-reserve'),
|
||||
icon: Icons.calendar_month_rounded,
|
||||
color: AppColors.blue,
|
||||
label: l10n.reserve,
|
||||
onTap: () => _openPage(context, const ReservePage()),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _toolButton({
|
||||
required Key key,
|
||||
required IconData icon,
|
||||
required Color color,
|
||||
required String label,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return Material(
|
||||
color: AppColors.card,
|
||||
borderRadius: BorderRadius.circular(_toolbarRadius),
|
||||
child: InkWell(
|
||||
key: key,
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(_toolbarRadius),
|
||||
child: Container(
|
||||
height: _toolbarHeight,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(_toolbarRadius),
|
||||
border: Border.all(color: AppColors.border),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(icon, size: 16, color: color),
|
||||
const SizedBox(width: 4),
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: AppColors.onSurface,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget _toolbar() {
|
||||
return DiscoverToolbar(onOpen: (page) => _openPage(context, page));
|
||||
}
|
||||
|
||||
void _openPage(BuildContext context, Widget page) {
|
||||
@@ -601,27 +462,3 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
AppRootTab.mine => DiscoverPageAction.mine,
|
||||
};
|
||||
}
|
||||
|
||||
/// 分类 tab 的弧形选中线。
|
||||
class CategoryUnderlinePainter extends CustomPainter {
|
||||
const CategoryUnderlinePainter({required this.color});
|
||||
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()
|
||||
..color = color
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = _categoryUnderlineStrokeWidth
|
||||
..strokeCap = StrokeCap.round;
|
||||
final path = Path()
|
||||
..moveTo(1, 1)
|
||||
..quadraticBezierTo(size.width / 2, size.height + 1, size.width - 1, 1);
|
||||
canvas.drawPath(path, paint);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant CategoryUnderlinePainter oldDelegate) =>
|
||||
color != oldDelegate.color;
|
||||
}
|
||||
@@ -139,7 +139,7 @@ class _SearchPageState extends State<SearchPage> {
|
||||
color: AppColors.textSecondary,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: AppDimens.spaceSm),
|
||||
const SizedBox(width: 2),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
key: const Key('discover-search'),
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// Author: fruit.com.cn
|
||||
// 剧场顶部分类标签和选中下划线。
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
|
||||
const double _selectedFontSize = 16;
|
||||
const double _fontSize = 15;
|
||||
const double _underlineWidth = 20;
|
||||
const double _underlineHeight = 3;
|
||||
const double _underlineStrokeWidth = 2;
|
||||
|
||||
/// 一个可横向滚动的分类标签。
|
||||
class DiscoverCategoryTab extends StatelessWidget {
|
||||
const DiscoverCategoryTab({
|
||||
super.key,
|
||||
required this.id,
|
||||
required this.anchorKey,
|
||||
required this.label,
|
||||
required this.selected,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final GlobalKey anchorKey;
|
||||
final String label;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return KeyedSubtree(
|
||||
key: anchorKey,
|
||||
child: GestureDetector(
|
||||
key: Key('theater-category-$id'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onTap,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
style: TextStyle(
|
||||
color: selected ? AppColors.onSurface : AppColors.muted,
|
||||
fontSize: selected ? _selectedFontSize : _fontSize,
|
||||
fontWeight: selected ? FontWeight.w800 : FontWeight.w500,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
CustomPaint(
|
||||
key: Key('theater-category-underline-$id'),
|
||||
size: const Size(_underlineWidth, _underlineHeight),
|
||||
painter: CategoryUnderlinePainter(
|
||||
color: selected ? AppColors.blue : AppColors.transparent,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 分类 tab 的弧形选中线。
|
||||
class CategoryUnderlinePainter extends CustomPainter {
|
||||
const CategoryUnderlinePainter({required this.color});
|
||||
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()
|
||||
..color = color
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = _underlineStrokeWidth
|
||||
..strokeCap = StrokeCap.round;
|
||||
final path = Path()
|
||||
..moveTo(1, 1)
|
||||
..quadraticBezierTo(size.width / 2, size.height + 1, size.width - 1, 1);
|
||||
canvas.drawPath(path, paint);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant CategoryUnderlinePainter oldDelegate) =>
|
||||
color != oldDelegate.color;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Author: fruit.com.cn
|
||||
// 剧场页筛选、排行、新剧、预约四个入口。
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
import '../../filter/filter_page.dart';
|
||||
import '../../new_releases/new_releases_page.dart';
|
||||
import '../../ranking/ranking_page.dart';
|
||||
import '../../reserve/reserve_page.dart';
|
||||
|
||||
const double _toolbarHeight = 36;
|
||||
const double _toolbarGap = 10;
|
||||
const double _toolbarRadius = 10;
|
||||
const Color _filterIconColor = AppColors.blueSoft;
|
||||
const Color _newIconColor = AppColors.blueSoft;
|
||||
|
||||
/// 剧场工具条。点按后由调用方打开对应页面。
|
||||
class DiscoverToolbar extends StatelessWidget {
|
||||
const DiscoverToolbar({super.key, required this.onOpen});
|
||||
|
||||
final void Function(Widget page) onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(14, 2, 14, 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _button(
|
||||
key: const Key('theater-toolbar-filter'),
|
||||
icon: Icons.tune_rounded,
|
||||
color: _filterIconColor,
|
||||
label: l10n.filter,
|
||||
onTap: () => onOpen(const FilterPage()),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _toolbarGap),
|
||||
Expanded(
|
||||
child: _button(
|
||||
key: const Key('theater-toolbar-ranking'),
|
||||
icon: Icons.local_fire_department_rounded,
|
||||
color: AppColors.blue,
|
||||
label: l10n.rankingTab,
|
||||
onTap: () => onOpen(const RankingPage()),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _toolbarGap),
|
||||
Expanded(
|
||||
child: _button(
|
||||
key: const Key('theater-toolbar-new'),
|
||||
icon: Icons.play_circle_fill_rounded,
|
||||
color: _newIconColor,
|
||||
label: l10n.newDramas,
|
||||
onTap: () => onOpen(const NewReleasesPage()),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _toolbarGap),
|
||||
Expanded(
|
||||
child: _button(
|
||||
key: const Key('theater-toolbar-reserve'),
|
||||
icon: Icons.calendar_month_rounded,
|
||||
color: AppColors.blue,
|
||||
label: l10n.reserve,
|
||||
onTap: () => onOpen(const ReservePage()),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _button({
|
||||
required Key key,
|
||||
required IconData icon,
|
||||
required Color color,
|
||||
required String label,
|
||||
required VoidCallback onTap,
|
||||
}) {
|
||||
return Material(
|
||||
color: AppColors.card,
|
||||
borderRadius: BorderRadius.circular(_toolbarRadius),
|
||||
child: InkWell(
|
||||
key: key,
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(_toolbarRadius),
|
||||
child: Container(
|
||||
height: _toolbarHeight,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(_toolbarRadius),
|
||||
border: Border.all(color: AppColors.border),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(icon, size: 16, color: color),
|
||||
const SizedBox(width: 4),
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: AppColors.onSurface,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -96,9 +96,9 @@ class DramaGridCard extends StatelessWidget {
|
||||
children: [
|
||||
_cover(),
|
||||
const SizedBox(height: _titleGap),
|
||||
_title(),
|
||||
_title(context),
|
||||
const SizedBox(height: _tagsGap),
|
||||
_tags(),
|
||||
_tags(context),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -151,9 +151,9 @@ class DramaGridCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _title() {
|
||||
Widget _title(BuildContext context) {
|
||||
return Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
key: Key('home-drama-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -166,8 +166,8 @@ class DramaGridCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _tags() {
|
||||
final tags = _tagValues();
|
||||
Widget _tags(BuildContext context) {
|
||||
final tags = _tagValues(context);
|
||||
if (tags.isEmpty) return const SizedBox.shrink();
|
||||
return Wrap(
|
||||
spacing: 6,
|
||||
@@ -193,7 +193,9 @@ class DramaGridCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _tagValues() {
|
||||
List<String> _tagValues(BuildContext context) {
|
||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
||||
final result = <String>[];
|
||||
for (final value in [drama.genre, drama.category]) {
|
||||
for (final part in value.split(_tagSplitter)) {
|
||||
|
||||
@@ -16,7 +16,7 @@ class SearchResultCard extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tags = _tags();
|
||||
final tags = _tags(context);
|
||||
return Material(
|
||||
key: Key('search-result-card-${drama.id}'),
|
||||
color: AppColors.transparent,
|
||||
@@ -60,7 +60,7 @@ class SearchResultCard extends StatelessWidget {
|
||||
),
|
||||
const SizedBox(height: AppDimens.searchResultTitleGap),
|
||||
Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
key: Key('search-result-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -92,7 +92,9 @@ class SearchResultCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _tags() {
|
||||
List<String> _tags(BuildContext context) {
|
||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
||||
final seen = <String>{};
|
||||
return [drama.genre, drama.category]
|
||||
.expand((value) => value.split(RegExp(r'[,/、·]')))
|
||||
|
||||
@@ -16,6 +16,7 @@ import '../../core/platform/haptics.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
import '../../core/theme/app_dimens.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../../core/widgets/app_glow_panel.dart';
|
||||
import '../../core/widgets/app_pull_to_refresh.dart';
|
||||
import '../../core/widgets/auth_gate.dart';
|
||||
import '../../core/widgets/empty_state.dart';
|
||||
@@ -181,15 +182,15 @@ class _DownloadsBody extends StatelessWidget {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(l10n.clearDownloadsTitle),
|
||||
content: Text(l10n.clearDownloadsMessage),
|
||||
builder: (dialogContext) => AppGlowDialog(
|
||||
title: l10n.clearDownloadsTitle,
|
||||
content: l10n.clearDownloadsMessage,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(true),
|
||||
child: Text(l10n.confirmClear),
|
||||
),
|
||||
@@ -435,7 +436,7 @@ class _LicenseTile extends StatelessWidget {
|
||||
minHeight: AppDimens.progressHeight,
|
||||
value: progress.clamp(0.0, 1.0),
|
||||
backgroundColor: AppColors.border,
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.blueSoft),
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.brandRed),
|
||||
),
|
||||
),
|
||||
if (license.expireAt != null) ...[
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -163,8 +163,10 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
||||
synopsis: localizedDramaSynopsis(l10n, drama),
|
||||
),
|
||||
),
|
||||
if (_tagValues(drama).isNotEmpty)
|
||||
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(drama))),
|
||||
if (_tagValues(context, drama).isNotEmpty)
|
||||
SliverToBoxAdapter(
|
||||
child: DramaTags(tags: _tagValues(context, drama)),
|
||||
),
|
||||
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
||||
],
|
||||
@@ -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)));
|
||||
@@ -442,13 +447,20 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
||||
return record.fraction;
|
||||
}
|
||||
|
||||
List<String> _tagValues(Drama drama) {
|
||||
List<String> _tagValues(BuildContext context, Drama drama) {
|
||||
final localized = drama.localizedTypeLabels(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
);
|
||||
final result = <String>[];
|
||||
for (final source in [drama.category, drama.genre]) {
|
||||
for (final part in source.split(_tagSplitter)) {
|
||||
final value = part.trim();
|
||||
if (value.isNotEmpty && !result.contains(value)) result.add(value);
|
||||
if (result.length == _maxTags) return result;
|
||||
if (localized.isNotEmpty) {
|
||||
result.addAll(localized.take(_maxTags));
|
||||
} else {
|
||||
for (final source in [drama.category, drama.genre]) {
|
||||
for (final part in source.split(_tagSplitter)) {
|
||||
final value = part.trim();
|
||||
if (value.isNotEmpty && !result.contains(value)) result.add(value);
|
||||
if (result.length == _maxTags) return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
final language = drama.language.trim();
|
||||
|
||||
@@ -95,7 +95,7 @@ class DramaResumeBar extends StatelessWidget {
|
||||
value: fraction,
|
||||
minHeight: 3,
|
||||
backgroundColor: AppColors.border,
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.blue),
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.brandRed),
|
||||
),
|
||||
),
|
||||
if (label != null) ...[
|
||||
|
||||
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
|
||||
import '../../../core/data/models/drama.dart';
|
||||
import '../../../core/formatting/localized_content.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../core/widgets/remote_image.dart';
|
||||
import '../../../core/widgets/subpage_header.dart';
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
@@ -54,7 +53,18 @@ class DramaDetailHeader extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
key: const Key('detail-hero'),
|
||||
decoration: const BoxDecoration(gradient: AppTheme.pageGradient),
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
AppColors.followingGlow,
|
||||
AppColors.followingGlowMid,
|
||||
AppColors.appBackground,
|
||||
],
|
||||
stops: [0, 0.14, 0.3],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: Padding(
|
||||
|
||||
@@ -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,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')),
|
||||
@@ -176,6 +172,8 @@ class _FavoritesBody extends StatelessWidget {
|
||||
],
|
||||
PagedListFooter(
|
||||
loading: favorites.loadingMore,
|
||||
hasMore: favorites.hasMore,
|
||||
hasItems: favorites.cards.isNotEmpty,
|
||||
errorMessage: favorites.loadMoreError == null
|
||||
? null
|
||||
: errorText(l10n, favorites.loadMoreError, l10n.favoritesError),
|
||||
@@ -265,8 +263,9 @@ class _FavoriteCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final tags = _tags();
|
||||
final synopsis = drama.synopsis.trim();
|
||||
final languageCode = Localizations.localeOf(context).languageCode;
|
||||
final tags = _tags(languageCode);
|
||||
final synopsis = drama.localizedSynopsis(languageCode).trim();
|
||||
return Container(
|
||||
key: ValueKey('favorite-card-${drama.id}'),
|
||||
decoration: BoxDecoration(
|
||||
@@ -309,7 +308,7 @@ class _FavoriteCard extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(languageCode),
|
||||
key: ValueKey('favorite-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -444,7 +443,9 @@ class _FavoriteCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _tags() {
|
||||
List<String> _tags(String languageCode) {
|
||||
final localized = drama.localizedTypeLabels(languageCode);
|
||||
if (localized.isNotEmpty) return localized.take(_maxTags).toList();
|
||||
final values = <String>[];
|
||||
for (final source in [drama.genre, drama.category]) {
|
||||
for (final part in source.split(_tagSplitter)) {
|
||||
|
||||
@@ -25,67 +25,6 @@ const double _barHorizontal = 16;
|
||||
const double _barFontSize = 13;
|
||||
const double _barButtonHeight = 30;
|
||||
const double _removeDialogButtonHeight = 32;
|
||||
const double _removeDialogRadius = 6;
|
||||
const double _removeDialogBottomInset = 8;
|
||||
|
||||
/// 播放历史移除确认。只把移除按钮压矮。
|
||||
Future<bool> confirmHistoryRemove(BuildContext context) async {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
actionsPadding: const EdgeInsets.fromLTRB(
|
||||
24,
|
||||
0,
|
||||
16,
|
||||
_removeDialogBottomInset,
|
||||
),
|
||||
content: Text(l10n.confirmRemove),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
minimumSize: const Size(0, _removeDialogButtonHeight),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(_removeDialogRadius),
|
||||
),
|
||||
),
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.remove),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
|
||||
/// 确认后返回是否取消已选追剧。
|
||||
Future<bool> confirmCancelFollowing(BuildContext context) async {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
content: Text(l10n.confirmCancelFollowing),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.cancelFollowing),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
|
||||
/// 只在追剧编辑中显示底栏。
|
||||
class FollowingEditSlot extends StatelessWidget {
|
||||
@@ -175,6 +114,7 @@ class FollowingEditBar extends StatelessWidget {
|
||||
TextButton(
|
||||
key: const Key('following-select-all'),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: AppColors.brandRed,
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
minimumSize: const Size(0, _barButtonHeight),
|
||||
@@ -194,16 +134,14 @@ class FollowingEditBar extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(
|
||||
TextButton(
|
||||
key: const Key('following-cancel-follow'),
|
||||
style: FilledButton.styleFrom(
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: AppColors.brandRed,
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
minimumSize: const Size(0, _removeDialogButtonHeight),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(_removeDialogRadius),
|
||||
),
|
||||
textStyle: const TextStyle(
|
||||
fontSize: _barFontSize,
|
||||
fontWeight: FontWeight.w600,
|
||||
|
||||
@@ -5,12 +5,18 @@ import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/data/models/watch_record.dart';
|
||||
import '../../core/data/services/favorite_controller.dart';
|
||||
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/empty_state.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../player/open_player.dart';
|
||||
import 'following_grid_card.dart';
|
||||
import 'following_paged_grid.dart';
|
||||
import 'widgets/continue_watching_banner.dart';
|
||||
|
||||
/// 追剧编辑中的选中状态。
|
||||
class FollowingFavoriteSelection {
|
||||
@@ -30,15 +36,19 @@ class FollowingFavoritesGrid extends StatelessWidget {
|
||||
const FollowingFavoritesGrid({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.history,
|
||||
required this.selection,
|
||||
required this.scrollController,
|
||||
required this.onGoHome,
|
||||
required this.onContinueRecord,
|
||||
});
|
||||
|
||||
final FavoriteController controller;
|
||||
final WatchRecordsController history;
|
||||
final FollowingFavoriteSelection selection;
|
||||
final ScrollController scrollController;
|
||||
final VoidCallback onGoHome;
|
||||
final ValueChanged<WatchRecord> onContinueRecord;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -49,7 +59,7 @@ class FollowingFavoritesGrid extends StatelessWidget {
|
||||
valueListenable: selection.selected,
|
||||
builder: (context, picked, _) {
|
||||
return ListenableBuilder(
|
||||
listenable: controller,
|
||||
listenable: Listenable.merge([controller, history]),
|
||||
builder: (context, _) => _grid(context, isEditing, picked),
|
||||
);
|
||||
},
|
||||
@@ -60,14 +70,15 @@ class FollowingFavoritesGrid extends StatelessWidget {
|
||||
|
||||
Widget _grid(BuildContext context, bool isEditing, Set<String> picked) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final extra = isEditing ? 0 : 1;
|
||||
final hasFavorites = controller.cards.isNotEmpty;
|
||||
final extra = !isEditing && hasFavorites ? 1 : 0;
|
||||
return FollowingPagedGrid(
|
||||
key: const Key('following-favorites-grid'),
|
||||
scrollController: scrollController,
|
||||
loading: controller.loading,
|
||||
loadingMore: controller.loadingMore,
|
||||
hasMore: controller.hasMore,
|
||||
hasItems: controller.cards.isNotEmpty,
|
||||
hasItems: hasFavorites,
|
||||
showInitialLoading: false,
|
||||
errorMessage: controller.error == null
|
||||
? null
|
||||
@@ -78,31 +89,107 @@ class FollowingFavoritesGrid extends StatelessWidget {
|
||||
onRefresh: controller.load,
|
||||
onLoadMore: controller.loadMore,
|
||||
itemCount: controller.cards.length + extra,
|
||||
empty: const SizedBox.shrink(),
|
||||
topSlivers: _topSlivers(context),
|
||||
empty: EmptyState(
|
||||
key: const Key('following-favorites-empty'),
|
||||
icon: Icons.bookmark_border_rounded,
|
||||
title: l10n.noFavoritesYet,
|
||||
),
|
||||
itemBuilder: (context, index) => _item(context, index, isEditing, picked),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _topSlivers(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final continueRecord = _continueRecord();
|
||||
return [
|
||||
if (continueRecord != null)
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppDimens.feedPageHorizontal,
|
||||
4,
|
||||
AppDimens.feedPageHorizontal,
|
||||
0,
|
||||
),
|
||||
child: ContinueWatchingBanner(
|
||||
record: continueRecord,
|
||||
languageCode: Localizations.localeOf(context).languageCode,
|
||||
onTap: () => onContinueRecord(continueRecord),
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppDimens.feedPageHorizontal,
|
||||
AppDimens.followingSectionTopGap,
|
||||
AppDimens.feedPageHorizontal,
|
||||
AppDimens.followingSectionBottomGap,
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
l10n.favoriteDramas,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: AppDimens.followingSectionTitleFont,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 2),
|
||||
child: Text(
|
||||
l10n.totalDramasCount(controller.total),
|
||||
style: const TextStyle(
|
||||
color: AppColors.textTabInactive,
|
||||
fontSize: AppDimens.followingSectionCountFont,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// 最近一条观看记录(records 已按最近观看排序,与观看历史页首条一致)。
|
||||
WatchRecord? _continueRecord() {
|
||||
return history.records.isEmpty ? null : history.records.first;
|
||||
}
|
||||
|
||||
Widget _item(
|
||||
BuildContext context,
|
||||
int index,
|
||||
bool isEditing,
|
||||
Set<String> picked,
|
||||
) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
if (index == controller.cards.length) {
|
||||
return FollowingAddCard(onTap: onGoHome);
|
||||
}
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final drama = controller.cards[index];
|
||||
final record = history.recordForDrama(drama.id);
|
||||
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
|
||||
final watchedEpisode = record?.episodeNumber ?? 0;
|
||||
final total = drama.episodeCount;
|
||||
final subtitle = watchedEpisode > 0 && total > 0
|
||||
? l10n.watchedEpisodeTotal(watchedEpisode, total)
|
||||
: l10n.favoriteEpisodeProgress(episode, total);
|
||||
return FollowingGridCard(
|
||||
dramaId: drama.id,
|
||||
title: drama.title,
|
||||
title: drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
posterUrl: drama.posterUrl,
|
||||
viewCount: drama.viewCount,
|
||||
editing: isEditing,
|
||||
selected: isEditing ? picked.contains(drama.id) : null,
|
||||
subtitle: l10n.favoriteEpisodeProgress(episode, drama.episodeCount),
|
||||
subtitle: subtitle,
|
||||
// TODO(backend): Drama 增加 hasUpdate / latestEpisodeNumber / isFinished
|
||||
// 字段后,在此传 updateBadge(l10n.hasUpdateBadge)、红色更新副标题
|
||||
// (l10n.updatedToEpisode)或灰色完结副标题(l10n.finishedAllEpisodes)。
|
||||
onTap: () => _openOrToggle(context, drama.id, isEditing),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ class FollowingGridCard extends StatelessWidget {
|
||||
this.editing = false,
|
||||
this.selected,
|
||||
this.onRemove,
|
||||
this.updateBadge,
|
||||
this.subtitleColor,
|
||||
});
|
||||
|
||||
final String dramaId;
|
||||
@@ -38,6 +40,13 @@ class FollowingGridCard extends StatelessWidget {
|
||||
final bool? selected;
|
||||
final VoidCallback? onRemove;
|
||||
|
||||
/// 左上角「有更新」角标文案;null 不显示。
|
||||
/// 待后端在 Drama 增加更新状态字段后由收藏网格传入。
|
||||
final String? updateBadge;
|
||||
|
||||
/// 副标题颜色;更新中用强调红,完结用默认灰。
|
||||
final Color? subtitleColor;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
@@ -109,6 +118,32 @@ class FollowingGridCard extends StatelessWidget {
|
||||
count: viewCount,
|
||||
),
|
||||
),
|
||||
if (updateBadge != null && selected == null)
|
||||
Positioned(
|
||||
left: AppDimens.followingBadgeInset,
|
||||
top: AppDimens.followingBadgeInset,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppDimens.followingBadgePaddingH,
|
||||
vertical: AppDimens.followingBadgePaddingV,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.brandRed,
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppDimens.followingBadgeRadius,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
updateBadge!,
|
||||
style: const TextStyle(
|
||||
color: AppColors.onPrimary,
|
||||
fontSize: AppDimens.followingBadgeFont,
|
||||
fontWeight: FontWeight.w400,
|
||||
height: 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (progress != null)
|
||||
Positioned(
|
||||
left: 0,
|
||||
@@ -120,7 +155,7 @@ class FollowingGridCard extends StatelessWidget {
|
||||
minHeight: AppDimens.followingProgressHeight,
|
||||
backgroundColor: AppColors.inactiveTrack,
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(
|
||||
AppColors.primary,
|
||||
AppColors.brandRed,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -130,13 +165,13 @@ class FollowingGridCard extends StatelessWidget {
|
||||
const SizedBox(height: AppDimens.cardCoverTitleGap),
|
||||
Text(
|
||||
title,
|
||||
maxLines: 2,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.left,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: AppDimens.cardTitleFont,
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: AppDimens.followingCardTitleFontNew,
|
||||
fontWeight: FontWeight.w400,
|
||||
height: AppDimens.cardTitleLineHeight,
|
||||
),
|
||||
),
|
||||
@@ -146,9 +181,9 @@ class FollowingGridCard extends StatelessWidget {
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.left,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textTertiary,
|
||||
fontSize: AppDimens.followingSubtitleFont,
|
||||
style: TextStyle(
|
||||
color: subtitleColor ?? AppColors.textTertiary,
|
||||
fontSize: AppDimens.followingCardSubtitleFontNew,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -169,9 +204,9 @@ class _SelectMark extends StatelessWidget {
|
||||
height: _selectMarkSize,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: selected ? AppColors.blue : AppColors.transparent,
|
||||
color: selected ? AppColors.brandRed : AppColors.transparent,
|
||||
border: Border.all(
|
||||
color: selected ? AppColors.blue : AppColors.textPrimary,
|
||||
color: selected ? AppColors.brandRed : AppColors.textPrimary,
|
||||
width: _selectBorderWidth,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -158,7 +158,7 @@ class FollowingHistoryCard extends StatelessWidget {
|
||||
minHeight: AppDimens.followingHistoryProgressHeight,
|
||||
backgroundColor: AppColors.inactiveTrack,
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(
|
||||
AppColors.primary,
|
||||
AppColors.brandRed,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user