Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67e178c89d |
No files matched your search
@@ -11,7 +11,6 @@
|
|||||||
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
|
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
|
||||||
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
||||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
|
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 */; };
|
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
|
||||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
||||||
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
|
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
|
||||||
@@ -50,7 +49,6 @@
|
|||||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
|
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>"; };
|
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>"; };
|
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>"; };
|
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>"; };
|
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>"; };
|
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
|
||||||
@@ -124,7 +122,6 @@
|
|||||||
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
|
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
|
||||||
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
|
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
|
||||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
|
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
|
||||||
8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */,
|
|
||||||
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
|
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
|
||||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
|
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
|
||||||
);
|
);
|
||||||
@@ -285,7 +282,6 @@
|
|||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
|
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
|
||||||
8C4E1A022F9A4B1000C636F3 /* WirelessDataPrompt.swift in Sources */,
|
|
||||||
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
|
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
|
||||||
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
|
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ final class RunnerFlutterViewController: FlutterViewController {
|
|||||||
|
|
||||||
@main
|
@main
|
||||||
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
||||||
private let wirelessDataPrompt = WirelessDataPrompt()
|
|
||||||
private let thumbnailQueue = DispatchQueue(
|
private let thumbnailQueue = DispatchQueue(
|
||||||
label: "com.stormg.lumadrama.thumbnail",
|
label: "com.stormg.lumadrama.thumbnail",
|
||||||
qos: .userInitiated
|
qos: .userInitiated
|
||||||
@@ -51,18 +50,8 @@ final class RunnerFlutterViewController: FlutterViewController {
|
|||||||
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
||||||
}
|
}
|
||||||
|
|
||||||
override func applicationDidBecomeActive(_ application: UIApplication) {
|
|
||||||
super.applicationDidBecomeActive(application)
|
|
||||||
requestWirelessDataPrompt()
|
|
||||||
}
|
|
||||||
|
|
||||||
func requestWirelessDataPrompt() {
|
|
||||||
wirelessDataPrompt.requestSystemPrompt()
|
|
||||||
}
|
|
||||||
|
|
||||||
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||||
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
||||||
registerWirelessDataChannel(engineBridge)
|
|
||||||
let channel = FlutterMethodChannel(
|
let channel = FlutterMethodChannel(
|
||||||
name: "com.stormg.lumadrama/share",
|
name: "com.stormg.lumadrama/share",
|
||||||
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
||||||
@@ -143,22 +132,4 @@ final class RunnerFlutterViewController: FlutterViewController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,6 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import Flutter
|
import Flutter
|
||||||
import UIKit
|
import UIKit
|
||||||
|
|
||||||
class SceneDelegate: FlutterSceneDelegate {
|
class SceneDelegate: FlutterSceneDelegate {
|
||||||
override func sceneDidBecomeActive(_ scene: UIScene) {
|
|
||||||
super.sceneDidBecomeActive(scene)
|
|
||||||
(UIApplication.shared.delegate as? AppDelegate)?.requestWirelessDataPrompt()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
// 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) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+5
-36
@@ -30,7 +30,6 @@ import 'core/data/repositories/favorite_repository.dart';
|
|||||||
import 'core/data/repositories/interaction_repository.dart';
|
import 'core/data/repositories/interaction_repository.dart';
|
||||||
import 'core/data/repositories/notice_repository.dart';
|
import 'core/data/repositories/notice_repository.dart';
|
||||||
import 'core/data/repositories/playback_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/search_repository.dart';
|
||||||
import 'core/data/repositories/store_repository.dart';
|
import 'core/data/repositories/store_repository.dart';
|
||||||
import 'core/data/repositories/watch_history_repository.dart';
|
import 'core/data/repositories/watch_history_repository.dart';
|
||||||
@@ -42,7 +41,6 @@ import 'core/data/services/download_controller.dart';
|
|||||||
import 'core/data/services/favorite_controller.dart';
|
import 'core/data/services/favorite_controller.dart';
|
||||||
import 'core/data/services/interaction_controller.dart';
|
import 'core/data/services/interaction_controller.dart';
|
||||||
import 'core/data/services/locale_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/event_tracker.dart';
|
||||||
import 'core/data/services/playback_position_cache.dart';
|
import 'core/data/services/playback_position_cache.dart';
|
||||||
import 'core/data/services/playback_session.dart';
|
import 'core/data/services/playback_session.dart';
|
||||||
@@ -85,7 +83,6 @@ class LumaDramaApp extends StatefulWidget {
|
|||||||
this.commerceRepository,
|
this.commerceRepository,
|
||||||
this.storeRepository,
|
this.storeRepository,
|
||||||
this.searchRepository,
|
this.searchRepository,
|
||||||
this.playlistRepository,
|
|
||||||
this.haptics = const FlutterHaptics(),
|
this.haptics = const FlutterHaptics(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -106,7 +103,6 @@ class LumaDramaApp extends StatefulWidget {
|
|||||||
final CommerceRepository? commerceRepository;
|
final CommerceRepository? commerceRepository;
|
||||||
final StoreRepository? storeRepository;
|
final StoreRepository? storeRepository;
|
||||||
final SearchRepository? searchRepository;
|
final SearchRepository? searchRepository;
|
||||||
final PlaylistRepository? playlistRepository;
|
|
||||||
final Haptics haptics;
|
final Haptics haptics;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -130,10 +126,8 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
_sessionStore,
|
_sessionStore,
|
||||||
);
|
);
|
||||||
|
|
||||||
late final CatalogApi _catalogApi = CatalogApi(_apiClient);
|
|
||||||
|
|
||||||
late final CatalogRepository _catalogRepository =
|
late final CatalogRepository _catalogRepository =
|
||||||
widget.catalogRepository ?? HttpCatalogRepository(_catalogApi);
|
widget.catalogRepository ?? HttpCatalogRepository(CatalogApi(_apiClient));
|
||||||
|
|
||||||
late final CategoryRepository _categoryRepository =
|
late final CategoryRepository _categoryRepository =
|
||||||
widget.categoryRepository ??
|
widget.categoryRepository ??
|
||||||
@@ -183,13 +177,6 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
late final SearchRepository _searchRepository =
|
late final SearchRepository _searchRepository =
|
||||||
widget.searchRepository ?? HttpSearchRepository(CatalogApi(_apiClient));
|
widget.searchRepository ?? HttpSearchRepository(CatalogApi(_apiClient));
|
||||||
|
|
||||||
/// 测试注入了目录仓库时不打剧单接口,剧单页继续用本地分区。
|
|
||||||
late final PlaylistRepository? _playlistRepository =
|
|
||||||
widget.playlistRepository ??
|
|
||||||
(widget.catalogRepository == null
|
|
||||||
? HttpPlaylistRepository(CatalogApi(_apiClient))
|
|
||||||
: null);
|
|
||||||
|
|
||||||
late final StoreRepository _storeRepository =
|
late final StoreRepository _storeRepository =
|
||||||
widget.storeRepository ?? HttpStoreRepository(CommerceApi(_apiClient));
|
widget.storeRepository ?? HttpStoreRepository(CommerceApi(_apiClient));
|
||||||
|
|
||||||
@@ -252,26 +239,14 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
CategoryController _createCategories() {
|
|
||||||
final controller = CategoryController(_categoryRepository);
|
|
||||||
if (widget.catalogRepository == null) {
|
|
||||||
controller.dramaPageLoader = CategoryApi(_apiClient).dramas;
|
|
||||||
}
|
|
||||||
controller.load();
|
|
||||||
return controller;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final playlists = _playlistRepository;
|
|
||||||
return MultiProvider(
|
return MultiProvider(
|
||||||
providers: [
|
providers: [
|
||||||
Provider(create: (_) => PlaybackCoordinator()),
|
Provider(create: (_) => PlaybackCoordinator()),
|
||||||
Provider<EventTracker>(create: (_) => EventTracker(_apiClient)),
|
Provider<EventTracker>(create: (_) => EventTracker(_apiClient)),
|
||||||
Provider<PlayerFactory>(create: (_) => widget.playerFactory),
|
Provider<PlayerFactory>(create: (_) => widget.playerFactory),
|
||||||
Provider<CatalogRepository>.value(value: _catalogRepository),
|
Provider<CatalogRepository>.value(value: _catalogRepository),
|
||||||
if (widget.catalogRepository == null)
|
|
||||||
Provider<CatalogApi>.value(value: _catalogApi),
|
|
||||||
Provider<PlaybackRepository>.value(value: _playback),
|
Provider<PlaybackRepository>.value(value: _playback),
|
||||||
Provider<PlaybackPositionCache>.value(value: _playbackPositionCache),
|
Provider<PlaybackPositionCache>.value(value: _playbackPositionCache),
|
||||||
Provider<WatchHistoryRepository>.value(value: _watchHistory),
|
Provider<WatchHistoryRepository>.value(value: _watchHistory),
|
||||||
@@ -285,17 +260,11 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
Provider<SearchRepository>.value(value: _searchRepository),
|
Provider<SearchRepository>.value(value: _searchRepository),
|
||||||
Provider<Haptics>.value(value: widget.haptics),
|
Provider<Haptics>.value(value: widget.haptics),
|
||||||
ChangeNotifierProvider(
|
ChangeNotifierProvider(
|
||||||
create: (_) {
|
create: (_) => CatalogController(_catalogRepository)..load(),
|
||||||
final catalog = CatalogController(_catalogRepository);
|
),
|
||||||
if (widget.catalogRepository != null) catalog.load();
|
ChangeNotifierProvider(
|
||||||
return catalog;
|
create: (_) => CategoryController(_categoryRepository)..load(),
|
||||||
},
|
|
||||||
),
|
),
|
||||||
ChangeNotifierProvider(create: (_) => _createCategories()),
|
|
||||||
if (playlists != null)
|
|
||||||
ChangeNotifierProvider(
|
|
||||||
create: (_) => PlaylistController(playlists),
|
|
||||||
),
|
|
||||||
ChangeNotifierProvider.value(value: _favoriteController),
|
ChangeNotifierProvider.value(value: _favoriteController),
|
||||||
ChangeNotifierProvider.value(value: _downloadController),
|
ChangeNotifierProvider.value(value: _downloadController),
|
||||||
ChangeNotifierProvider.value(value: _walletController),
|
ChangeNotifierProvider.value(value: _walletController),
|
||||||
|
|||||||
@@ -1,30 +1,17 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'locale_text.dart';
|
|
||||||
|
|
||||||
/// 服务端内容分类。id 按契约保持字符串,避免雪花 ID 精度丢失。
|
/// 服务端内容分类。id 按契约保持字符串,避免雪花 ID 精度丢失。
|
||||||
class ContentCategory {
|
class ContentCategory {
|
||||||
const ContentCategory({
|
const ContentCategory({required this.id, required this.name});
|
||||||
required this.id,
|
|
||||||
required this.name,
|
|
||||||
this.locales = const {},
|
|
||||||
});
|
|
||||||
|
|
||||||
final String id;
|
final String id;
|
||||||
|
|
||||||
/// 中文名称,与 locales 里的 zh 相同。
|
|
||||||
final String name;
|
final String name;
|
||||||
final Map<String, String> locales;
|
|
||||||
|
|
||||||
/// 解析 `GET /app/categories` 的单项。
|
/// 解析 `GET /app/categories` 的单项。
|
||||||
factory ContentCategory.fromJson(Map<String, dynamic> json) {
|
factory ContentCategory.fromJson(Map<String, dynamic> json) {
|
||||||
final locales = localeMap(json['locales']);
|
return ContentCategory(
|
||||||
final name = json['name'] as String? ?? locales['zh'] ?? '';
|
id: (json['id'] ?? '').toString(),
|
||||||
return ContentCategory(id: (json['id'] ?? '').toString(), name: name, locales: locales);
|
name: json['name'] as String? ?? '',
|
||||||
}
|
);
|
||||||
|
|
||||||
/// 按界面语言取名称。缺对应语言时回落到中文。
|
|
||||||
String localizedName(String languageCode) {
|
|
||||||
return localizedText(languageCode, name, locales);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'dart:ui';
|
|
||||||
|
|
||||||
import 'json_numbers.dart';
|
import 'json_numbers.dart';
|
||||||
import 'locale_text.dart';
|
|
||||||
|
|
||||||
/// 短剧与剧集,字段与后端 `/app/**` 的下发结构对应。
|
/// 短剧与剧集,字段与后端 `/app/**` 的下发结构对应。
|
||||||
///
|
///
|
||||||
@@ -21,7 +18,6 @@ class Episode {
|
|||||||
this.likeCount,
|
this.likeCount,
|
||||||
this.commentCount,
|
this.commentCount,
|
||||||
this.thumbnailsUrl,
|
this.thumbnailsUrl,
|
||||||
this.posterUrl,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final String id;
|
final String id;
|
||||||
@@ -38,14 +34,12 @@ class Episode {
|
|||||||
final int? likeCount;
|
final int? likeCount;
|
||||||
final int? commentCount;
|
final int? commentCount;
|
||||||
final String? thumbnailsUrl;
|
final String? thumbnailsUrl;
|
||||||
final String? posterUrl;
|
|
||||||
|
|
||||||
Episode withVideoUrl(
|
Episode withVideoUrl(
|
||||||
String url, {
|
String url, {
|
||||||
int? likeCount,
|
int? likeCount,
|
||||||
int? commentCount,
|
int? commentCount,
|
||||||
String? thumbnailsUrl,
|
String? thumbnailsUrl,
|
||||||
String? posterUrl,
|
|
||||||
}) => Episode(
|
}) => Episode(
|
||||||
id: id,
|
id: id,
|
||||||
number: number,
|
number: number,
|
||||||
@@ -57,21 +51,6 @@ class Episode {
|
|||||||
likeCount: likeCount ?? this.likeCount,
|
likeCount: likeCount ?? this.likeCount,
|
||||||
commentCount: commentCount ?? this.commentCount,
|
commentCount: commentCount ?? this.commentCount,
|
||||||
thumbnailsUrl: thumbnailsUrl ?? this.thumbnailsUrl,
|
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) {
|
factory Episode.fromJson(Map<String, dynamic> json) {
|
||||||
@@ -86,7 +65,6 @@ class Episode {
|
|||||||
likeCount: _optionalInt(json['likeCount']),
|
likeCount: _optionalInt(json['likeCount']),
|
||||||
commentCount: _optionalInt(json['commentCount']),
|
commentCount: _optionalInt(json['commentCount']),
|
||||||
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
|
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
|
||||||
posterUrl: _optionalString(json['posterUrl']),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,14 +76,7 @@ class Drama {
|
|||||||
required this.synopsis,
|
required this.synopsis,
|
||||||
required this.posterUrl,
|
required this.posterUrl,
|
||||||
this.episodes = const [],
|
this.episodes = const [],
|
||||||
this.titleLocales = const {},
|
|
||||||
this.synopsisLocales = const {},
|
|
||||||
this.tag = '',
|
|
||||||
this.tagLocales = const {},
|
|
||||||
this.tagColor = '',
|
|
||||||
this.category = '',
|
this.category = '',
|
||||||
this.categoryLocales = const {},
|
|
||||||
this.types = const [],
|
|
||||||
this.genre = '',
|
this.genre = '',
|
||||||
this.totalEpisodes = 0,
|
this.totalEpisodes = 0,
|
||||||
this.freeEpisodes = 0,
|
this.freeEpisodes = 0,
|
||||||
@@ -123,16 +94,9 @@ class Drama {
|
|||||||
final String id;
|
final String id;
|
||||||
final String title;
|
final String title;
|
||||||
final String synopsis;
|
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 String posterUrl;
|
||||||
final List<Episode> episodes;
|
final List<Episode> episodes;
|
||||||
final String category;
|
final String category;
|
||||||
final Map<String, String> categoryLocales;
|
|
||||||
final List<Map<String, String>> types;
|
|
||||||
final String genre;
|
final String genre;
|
||||||
final int totalEpisodes;
|
final int totalEpisodes;
|
||||||
final int freeEpisodes;
|
final int freeEpisodes;
|
||||||
@@ -163,26 +127,19 @@ class Drama {
|
|||||||
/// 列表卡片:带一集可播预览(首页直接起播),完整剧集进详情再取。
|
/// 列表卡片:带一集可播预览(首页直接起播),完整剧集进详情再取。
|
||||||
factory Drama.fromCardJson(Map<String, dynamic> json) {
|
factory Drama.fromCardJson(Map<String, dynamic> json) {
|
||||||
final preview = json['preview'];
|
final preview = json['preview'];
|
||||||
final text = _DramaText.fromJson(json);
|
|
||||||
return Drama(
|
return Drama(
|
||||||
id: (json['id'] ?? '').toString(),
|
id: (json['id'] ?? '').toString(),
|
||||||
title: text.title,
|
title: json['title'] as String? ?? '',
|
||||||
synopsis: text.synopsis,
|
synopsis: json['synopsis'] as String? ?? '',
|
||||||
titleLocales: text.titleLocales,
|
|
||||||
synopsisLocales: text.synopsisLocales,
|
|
||||||
tag: text.tag,
|
|
||||||
tagLocales: text.tagLocales,
|
|
||||||
tagColor: json['tagColor'] as String? ?? '',
|
|
||||||
posterUrl: json['cover'] as String? ?? '',
|
posterUrl: json['cover'] as String? ?? '',
|
||||||
episodes: preview is Map<String, dynamic>
|
episodes: preview is Map<String, dynamic>
|
||||||
? [Episode.fromJson(preview)]
|
? [Episode.fromJson(preview)]
|
||||||
: const [],
|
: const [],
|
||||||
category: text.category,
|
category: json['category'] as String? ?? '',
|
||||||
categoryLocales: text.categoryLocales,
|
genre: json['genre'] as String? ?? '',
|
||||||
types: text.types,
|
|
||||||
genre: text.genre,
|
|
||||||
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
||||||
isHot: json['isHot'] == true,
|
isHot: json['isHot'] == true,
|
||||||
|
// viewCount 后端是 Long,按字符串下发(见 json_numbers.dart)
|
||||||
viewCount: jsonToInt(json['viewCount']),
|
viewCount: jsonToInt(json['viewCount']),
|
||||||
likeCount: _optionalInt(json['likeCount']),
|
likeCount: _optionalInt(json['likeCount']),
|
||||||
favoriteCount: _optionalInt(json['favoriteCount']),
|
favoriteCount: _optionalInt(json['favoriteCount']),
|
||||||
@@ -195,21 +152,13 @@ class Drama {
|
|||||||
|
|
||||||
/// 详情:带剧集列表。
|
/// 详情:带剧集列表。
|
||||||
factory Drama.fromDetailJson(Map<String, dynamic> json) {
|
factory Drama.fromDetailJson(Map<String, dynamic> json) {
|
||||||
final text = _DramaText.fromJson(json);
|
|
||||||
return Drama(
|
return Drama(
|
||||||
id: (json['id'] ?? '').toString(),
|
id: (json['id'] ?? '').toString(),
|
||||||
title: text.title,
|
title: json['title'] as String? ?? '',
|
||||||
synopsis: text.synopsis,
|
synopsis: json['synopsis'] as String? ?? '',
|
||||||
titleLocales: text.titleLocales,
|
|
||||||
synopsisLocales: text.synopsisLocales,
|
|
||||||
tag: text.tag,
|
|
||||||
tagLocales: text.tagLocales,
|
|
||||||
tagColor: json['tagColor'] as String? ?? '',
|
|
||||||
posterUrl: json['cover'] as String? ?? '',
|
posterUrl: json['cover'] as String? ?? '',
|
||||||
category: text.category,
|
category: json['category'] as String? ?? '',
|
||||||
categoryLocales: text.categoryLocales,
|
genre: json['genre'] as String? ?? '',
|
||||||
types: text.types,
|
|
||||||
genre: text.genre,
|
|
||||||
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
||||||
freeEpisodes: (json['freeEpisodes'] as num?)?.toInt() ?? 0,
|
freeEpisodes: (json['freeEpisodes'] as num?)?.toInt() ?? 0,
|
||||||
isHot: json['isHot'] == true,
|
isHot: json['isHot'] == true,
|
||||||
@@ -227,37 +176,6 @@ class Drama {
|
|||||||
.toList(),
|
.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);
|
int? _optionalInt(dynamic value) => value == null ? null : jsonToInt(value);
|
||||||
@@ -266,81 +184,3 @@ String? _optionalString(dynamic value) {
|
|||||||
final text = value is String ? value.trim() : '';
|
final text = value is String ? value.trim() : '';
|
||||||
return text.isEmpty ? null : text;
|
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 : '';
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
// 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) {
|
factory FeedSection.fromJson(Map<String, dynamic> json) {
|
||||||
return FeedSection(
|
return FeedSection(
|
||||||
code: json['code'] as String? ?? '',
|
code: json['code'] as String? ?? '',
|
||||||
title: _sectionTitle(json),
|
title: json['title'] as String? ?? '',
|
||||||
dramas: (json['dramas'] as List? ?? const [])
|
dramas: (json['dramas'] as List? ?? const [])
|
||||||
.whereType<Map<String, dynamic>>()
|
.whereType<Map<String, dynamic>>()
|
||||||
.map(Drama.fromCardJson)
|
.map(Drama.fromCardJson)
|
||||||
@@ -84,12 +84,3 @@ 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,16 +58,14 @@ class LikeToggleResult {
|
|||||||
|
|
||||||
/// 控制器统一返回结果;失败消息可直接展示后端 `message`。
|
/// 控制器统一返回结果;失败消息可直接展示后端 `message`。
|
||||||
class OperationResult<T> {
|
class OperationResult<T> {
|
||||||
const OperationResult._(this.data, this.errorMessage, this.errorCode);
|
const OperationResult._(this.data, this.errorMessage);
|
||||||
|
|
||||||
const OperationResult.success([T? data]) : this._(data, null, null);
|
const OperationResult.success([T? data]) : this._(data, null);
|
||||||
|
|
||||||
const OperationResult.failure(this.errorMessage, {this.errorCode})
|
const OperationResult.failure(this.errorMessage) : data = null;
|
||||||
: data = null;
|
|
||||||
|
|
||||||
final T? data;
|
final T? data;
|
||||||
final String? errorMessage;
|
final String? errorMessage;
|
||||||
final int? errorCode;
|
|
||||||
|
|
||||||
bool get isSuccess => errorMessage == null;
|
bool get isSuccess => errorMessage == null;
|
||||||
}
|
}
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
// 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,7 +16,6 @@ class PlayTicket {
|
|||||||
this.qualities = const [],
|
this.qualities = const [],
|
||||||
this.tracks = const [],
|
this.tracks = const [],
|
||||||
this.thumbnailsUrl,
|
this.thumbnailsUrl,
|
||||||
this.posterUrl,
|
|
||||||
this.likeCount,
|
this.likeCount,
|
||||||
this.commentCount,
|
this.commentCount,
|
||||||
});
|
});
|
||||||
@@ -47,7 +46,6 @@ class PlayTicket {
|
|||||||
/// 各档签名地址。AUTO 是主列表,点选其它档位时换成对应地址。
|
/// 各档签名地址。AUTO 是主列表,点选其它档位时换成对应地址。
|
||||||
final List<PlayQualityTrack> tracks;
|
final List<PlayQualityTrack> tracks;
|
||||||
final String? thumbnailsUrl;
|
final String? thumbnailsUrl;
|
||||||
final String? posterUrl;
|
|
||||||
final int? likeCount;
|
final int? likeCount;
|
||||||
final int? commentCount;
|
final int? commentCount;
|
||||||
|
|
||||||
@@ -72,7 +70,6 @@ class PlayTicket {
|
|||||||
.toList(),
|
.toList(),
|
||||||
tracks: _tracks(json['tracks'], json['playUrl'] as String? ?? ''),
|
tracks: _tracks(json['tracks'], json['playUrl'] as String? ?? ''),
|
||||||
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
|
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
|
||||||
posterUrl: _optionalString(json['posterUrl']),
|
|
||||||
likeCount: json['likeCount'] == null
|
likeCount: json['likeCount'] == null
|
||||||
? null
|
? null
|
||||||
: jsonToInt(json['likeCount']),
|
: jsonToInt(json['likeCount']),
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
// 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,7 +1,6 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'json_numbers.dart';
|
import 'json_numbers.dart';
|
||||||
import 'locale_text.dart';
|
|
||||||
|
|
||||||
/// 服务端续看记录:`GET /app/watch/progress?dramaId=` 与 `/app/watch/recent` 的下发结构。
|
/// 服务端续看记录:`GET /app/watch/progress?dramaId=` 与 `/app/watch/recent` 的下发结构。
|
||||||
///
|
///
|
||||||
@@ -14,7 +13,6 @@ class WatchProgress {
|
|||||||
required this.position,
|
required this.position,
|
||||||
required this.duration,
|
required this.duration,
|
||||||
this.dramaTitle,
|
this.dramaTitle,
|
||||||
this.titleLocales = const {},
|
|
||||||
this.dramaCover,
|
this.dramaCover,
|
||||||
this.episodeNumber,
|
this.episodeNumber,
|
||||||
this.totalEpisodes,
|
this.totalEpisodes,
|
||||||
@@ -27,7 +25,6 @@ class WatchProgress {
|
|||||||
final String dramaId;
|
final String dramaId;
|
||||||
final String episodeId;
|
final String episodeId;
|
||||||
final String? dramaTitle;
|
final String? dramaTitle;
|
||||||
final Map<String, String> titleLocales;
|
|
||||||
final String? dramaCover;
|
final String? dramaCover;
|
||||||
final int? episodeNumber;
|
final int? episodeNumber;
|
||||||
final int? totalEpisodes;
|
final int? totalEpisodes;
|
||||||
@@ -48,17 +45,11 @@ class WatchProgress {
|
|||||||
return (position.inMilliseconds / duration.inMilliseconds).clamp(0.0, 1.0);
|
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) {
|
factory WatchProgress.fromJson(Map<String, dynamic> json) {
|
||||||
return WatchProgress(
|
return WatchProgress(
|
||||||
dramaId: (json['dramaId'] ?? '').toString(),
|
dramaId: (json['dramaId'] ?? '').toString(),
|
||||||
episodeId: (json['episodeId'] ?? '').toString(),
|
episodeId: (json['episodeId'] ?? '').toString(),
|
||||||
dramaTitle: json['dramaTitle']?.toString(),
|
dramaTitle: json['dramaTitle']?.toString(),
|
||||||
titleLocales: localeMap(json['titleLocales']),
|
|
||||||
dramaCover: json['dramaCover']?.toString(),
|
dramaCover: json['dramaCover']?.toString(),
|
||||||
episodeNumber: json['episodeNumber'] == null
|
episodeNumber: json['episodeNumber'] == null
|
||||||
? null
|
? null
|
||||||
@@ -81,7 +72,6 @@ class WatchProgress {
|
|||||||
'dramaId': dramaId,
|
'dramaId': dramaId,
|
||||||
'episodeId': episodeId,
|
'episodeId': episodeId,
|
||||||
if (dramaTitle != null) 'dramaTitle': dramaTitle,
|
if (dramaTitle != null) 'dramaTitle': dramaTitle,
|
||||||
if (titleLocales.isNotEmpty) 'titleLocales': titleLocales,
|
|
||||||
if (dramaCover != null) 'dramaCover': dramaCover,
|
if (dramaCover != null) 'dramaCover': dramaCover,
|
||||||
if (episodeNumber != null) 'episodeNumber': episodeNumber,
|
if (episodeNumber != null) 'episodeNumber': episodeNumber,
|
||||||
if (totalEpisodes != null) 'totalEpisodes': totalEpisodes,
|
if (totalEpisodes != null) 'totalEpisodes': totalEpisodes,
|
||||||
|
|||||||
@@ -31,13 +31,9 @@ class WatchRecord {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 服务端分页标题优先,详情标题作为回退。
|
/// 服务端分页标题优先,详情标题作为回退。
|
||||||
String get displayTitle => localizedDisplayTitle('zh');
|
String get displayTitle {
|
||||||
|
final pageTitle = progress.dramaTitle?.trim() ?? '';
|
||||||
/// 按当前语言取标题。分页语言表优先,详情语言表作为回退。
|
return pageTitle.isNotEmpty ? pageTitle : drama?.title.trim() ?? '';
|
||||||
String localizedDisplayTitle(String languageCode) {
|
|
||||||
final pageTitle = progress.localizedTitle(languageCode).trim();
|
|
||||||
if (pageTitle.isNotEmpty) return pageTitle;
|
|
||||||
return drama?.localizedTitle(languageCode).trim() ?? '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 服务端分页封面优先,详情封面作为回退。
|
/// 服务端分页封面优先,详情封面作为回退。
|
||||||
|
|||||||
@@ -134,7 +134,6 @@ class AuthApi {
|
|||||||
'platform': platform,
|
'platform': platform,
|
||||||
'osVersion': osVersion,
|
'osVersion': osVersion,
|
||||||
},
|
},
|
||||||
skipAuthRetry: true,
|
|
||||||
);
|
);
|
||||||
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import '../models/content_category.dart';
|
|
||||||
import '../models/drama.dart';
|
import '../models/drama.dart';
|
||||||
import '../models/feed_page.dart';
|
import '../models/feed_page.dart';
|
||||||
import '../models/home_feed.dart';
|
import '../models/home_feed.dart';
|
||||||
import '../models/page_result.dart';
|
|
||||||
import '../models/playlist_detail.dart';
|
|
||||||
import '../models/search_result.dart';
|
import '../models/search_result.dart';
|
||||||
import 'api_client.dart';
|
import 'api_client.dart';
|
||||||
|
|
||||||
@@ -61,95 +58,12 @@ class CatalogApi {
|
|||||||
return SearchResult.fromJson(_asMap(data));
|
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 {
|
Future<Drama> dramaDetail(String dramaId) async {
|
||||||
return Drama.fromDetailJson(
|
return Drama.fromDetailJson(
|
||||||
_asMap(await _client.get('/app/dramas/$dramaId')),
|
_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) {
|
Map<String, dynamic> _asMap(Object? data) {
|
||||||
if (data is Map<String, dynamic>) return data;
|
if (data is Map<String, dynamic>) return data;
|
||||||
throw const ApiException(-1, '返回数据格式异常');
|
throw const ApiException(-1, '返回数据格式异常');
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import '../models/content_category.dart';
|
import '../models/content_category.dart';
|
||||||
import '../models/drama.dart';
|
|
||||||
import '../models/page_result.dart';
|
|
||||||
import 'api_client.dart';
|
import 'api_client.dart';
|
||||||
|
|
||||||
/// 内容分类接口,对应契约 `GET /app/categories`。
|
/// 内容分类接口,对应契约 `GET /app/categories`。
|
||||||
class CategoryApi {
|
class CategoryApi {
|
||||||
const CategoryApi(this._client);
|
const CategoryApi(this._client);
|
||||||
|
|
||||||
static const int dramaPageSize = 20;
|
|
||||||
|
|
||||||
final ApiClient _client;
|
final ApiClient _client;
|
||||||
|
|
||||||
/// 拉取已启用分类,id 全程按字符串解析。
|
/// 拉取已启用分类,id 全程按字符串解析。
|
||||||
@@ -22,20 +18,4 @@ class CategoryApi {
|
|||||||
if (item is Map<String, dynamic>) ContentCategory.fromJson(item),
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import '../models/episode_stats.dart';
|
|
||||||
import '../models/play_ticket.dart';
|
import '../models/play_ticket.dart';
|
||||||
import 'api_client.dart';
|
import 'api_client.dart';
|
||||||
|
|
||||||
@@ -18,11 +17,4 @@ class PlaybackApi {
|
|||||||
if (data is Map<String, dynamic>) return PlayTicket.fromJson(data);
|
if (data is Map<String, dynamic>) return PlayTicket.fromJson(data);
|
||||||
throw const ApiException(-1, '返回数据格式异常');
|
throw const ApiException(-1, '返回数据格式异常');
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 轻量刷新互动计数:不签发地址,也不占用播放票据缓存。
|
|
||||||
Future<EpisodeStats> episodeStats(String episodeId) async {
|
|
||||||
final data = await _client.get('/app/episodes/$episodeId/stats');
|
|
||||||
if (data is Map<String, dynamic>) return EpisodeStats.fromJson(data);
|
|
||||||
throw const ApiException(-1, '返回数据格式异常');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import '../models/episode_stats.dart';
|
|
||||||
import '../models/play_ticket.dart';
|
import '../models/play_ticket.dart';
|
||||||
import '../remote/playback_api.dart';
|
import '../remote/playback_api.dart';
|
||||||
|
|
||||||
@@ -11,9 +10,6 @@ import '../remote/playback_api.dart';
|
|||||||
abstract interface class PlaybackRepository {
|
abstract interface class PlaybackRepository {
|
||||||
Future<PlayTicket> ticketFor(String episodeId, {bool forceRefresh = false});
|
Future<PlayTicket> ticketFor(String episodeId, {bool forceRefresh = false});
|
||||||
|
|
||||||
/// 读取互动计数快照;与 [ticketFor] 分离,避免为了刷新计数重新签发地址。
|
|
||||||
Future<EpisodeStats> episodeStats(String episodeId);
|
|
||||||
|
|
||||||
/// 当前缓存的票据是否还在有效期内(用于"回前台发现过期就重新取")。
|
/// 当前缓存的票据是否还在有效期内(用于"回前台发现过期就重新取")。
|
||||||
bool isFresh(String episodeId);
|
bool isFresh(String episodeId);
|
||||||
}
|
}
|
||||||
@@ -46,10 +42,6 @@ class HttpPlaybackRepository implements PlaybackRepository {
|
|||||||
return ticket;
|
return ticket;
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
|
||||||
Future<EpisodeStats> episodeStats(String episodeId) =>
|
|
||||||
_api.episodeStats(episodeId);
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
bool isFresh(String episodeId) {
|
bool isFresh(String episodeId) {
|
||||||
final cached = _cache[episodeId];
|
final cached = _cache[episodeId];
|
||||||
@@ -73,22 +65,11 @@ class _CachedTicket {
|
|||||||
|
|
||||||
/// 测试与离线场景用:按集返回固定票据,并记录被请求过几次。
|
/// 测试与离线场景用:按集返回固定票据,并记录被请求过几次。
|
||||||
class FakePlaybackRepository implements PlaybackRepository {
|
class FakePlaybackRepository implements PlaybackRepository {
|
||||||
FakePlaybackRepository({
|
FakePlaybackRepository({this.ticket, this.error, this.fresh = true});
|
||||||
this.ticket,
|
|
||||||
this.error,
|
|
||||||
this.fresh = true,
|
|
||||||
this.stats,
|
|
||||||
this.statsError,
|
|
||||||
Map<String, EpisodeStats>? statsByEpisode,
|
|
||||||
}) : statsByEpisode = statsByEpisode ?? {};
|
|
||||||
|
|
||||||
PlayTicket? ticket;
|
PlayTicket? ticket;
|
||||||
Object? error;
|
Object? error;
|
||||||
EpisodeStats? stats;
|
|
||||||
Object? statsError;
|
|
||||||
final Map<String, EpisodeStats> statsByEpisode;
|
|
||||||
final List<String> requests = [];
|
final List<String> requests = [];
|
||||||
final List<String> statsRequests = [];
|
|
||||||
final List<bool> forced = [];
|
final List<bool> forced = [];
|
||||||
|
|
||||||
/// 模拟"票据是否还有效":置 false 可验证回前台会重新取。
|
/// 模拟"票据是否还有效":置 false 可验证回前台会重新取。
|
||||||
@@ -114,13 +95,4 @@ class FakePlaybackRepository implements PlaybackRepository {
|
|||||||
qualities: const ['AUTO', '720P', '1080P'],
|
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');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
// 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);
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
// 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,6 @@ import '../../config/app_config.dart';
|
|||||||
import '../models/content_category.dart';
|
import '../models/content_category.dart';
|
||||||
import '../models/drama.dart';
|
import '../models/drama.dart';
|
||||||
import '../models/home_feed.dart';
|
import '../models/home_feed.dart';
|
||||||
import '../models/page_result.dart';
|
|
||||||
import '../remote/category_api.dart';
|
|
||||||
import '../repositories/category_repository.dart';
|
import '../repositories/category_repository.dart';
|
||||||
|
|
||||||
/// 剧场页数据:服务端分类清单与发现 feed。
|
/// 剧场页数据:服务端分类清单与发现 feed。
|
||||||
@@ -16,80 +14,13 @@ class CategoryController extends ChangeNotifier {
|
|||||||
|
|
||||||
final CategoryRepository _repository;
|
final CategoryRepository _repository;
|
||||||
|
|
||||||
/// 生产环境注入。未注入时首页分类继续用本地筛选。
|
|
||||||
Future<PageResult<Drama>> Function(
|
|
||||||
String categoryId, {
|
|
||||||
int pageIndex,
|
|
||||||
int pageSize,
|
|
||||||
})? dramaPageLoader;
|
|
||||||
|
|
||||||
List<ContentCategory> categories = const [];
|
List<ContentCategory> categories = const [];
|
||||||
final Map<String, CategoryDramaSlot> _slots = {};
|
|
||||||
HomeFeed feed = const HomeFeed();
|
HomeFeed feed = const HomeFeed();
|
||||||
bool loading = false;
|
bool loading = false;
|
||||||
String? error;
|
String? error;
|
||||||
String? debugError;
|
String? debugError;
|
||||||
bool _disposed = false;
|
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) {
|
List<Drama> dramasOf(String categoryId) {
|
||||||
final code = 'category-$categoryId';
|
final code = 'category-$categoryId';
|
||||||
@@ -99,23 +30,19 @@ class CategoryController extends ChangeNotifier {
|
|||||||
return const [];
|
return const [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 首页只拉分类,再拉第一个分类的短剧。发现页聚合留到没有短剧分页时再取。
|
/// 加载分类与发现 feed;失败保留可重试错误态。
|
||||||
Future<void> load() async {
|
Future<void> load() async {
|
||||||
loading = true;
|
loading = true;
|
||||||
error = null;
|
error = null;
|
||||||
debugError = null;
|
debugError = null;
|
||||||
_notify();
|
_notify();
|
||||||
try {
|
try {
|
||||||
if (dramaPageLoader != null) {
|
final results = await Future.wait<Object>([
|
||||||
categories = await _repository.fetchCategories();
|
_repository.fetchCategories(),
|
||||||
} else {
|
_repository.fetchDiscoverFeed(),
|
||||||
final results = await Future.wait<Object>([
|
]);
|
||||||
_repository.fetchCategories(),
|
categories = results[0] as List<ContentCategory>;
|
||||||
_repository.fetchDiscoverFeed(),
|
feed = results[1] as HomeFeed;
|
||||||
]);
|
|
||||||
categories = results[0] as List<ContentCategory>;
|
|
||||||
feed = results[1] as HomeFeed;
|
|
||||||
}
|
|
||||||
} catch (exception) {
|
} catch (exception) {
|
||||||
error = 'categoriesError';
|
error = 'categoriesError';
|
||||||
debugError = exception.toString();
|
debugError = exception.toString();
|
||||||
@@ -126,9 +53,6 @@ class CategoryController extends ChangeNotifier {
|
|||||||
loading = false;
|
loading = false;
|
||||||
_notify();
|
_notify();
|
||||||
}
|
}
|
||||||
if (error == null && dramaPageLoader != null && categories.isNotEmpty) {
|
|
||||||
await openCategory(categories.first.id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void _notify() {
|
void _notify() {
|
||||||
@@ -141,14 +65,3 @@ class CategoryController extends ChangeNotifier {
|
|||||||
super.dispose();
|
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,10 +197,7 @@ class CommentController extends ChangeNotifier {
|
|||||||
_insertPublished(comment, replyTo);
|
_insertPublished(comment, replyTo);
|
||||||
return OperationResult.success(comment);
|
return OperationResult.success(comment);
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
return OperationResult.failure(
|
return OperationResult.failure(_errorMessage(failure));
|
||||||
_errorMessage(failure),
|
|
||||||
errorCode: failure is ApiException ? failure.code : null,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
submitting = false;
|
submitting = false;
|
||||||
_notify();
|
_notify();
|
||||||
@@ -220,10 +217,7 @@ class CommentController extends ChangeNotifier {
|
|||||||
return const OperationResult.success();
|
return const OperationResult.success();
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
_restoreComment(comment, location);
|
_restoreComment(comment, location);
|
||||||
return OperationResult.failure(
|
return OperationResult.failure(_errorMessage(failure));
|
||||||
_errorMessage(failure),
|
|
||||||
errorCode: failure is ApiException ? failure.code : null,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
_deletingCommentIds.remove(comment.id);
|
_deletingCommentIds.remove(comment.id);
|
||||||
_notify();
|
_notify();
|
||||||
@@ -259,10 +253,7 @@ class CommentController extends ChangeNotifier {
|
|||||||
return OperationResult.success(result);
|
return OperationResult.success(result);
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
_replaceComment(current);
|
_replaceComment(current);
|
||||||
return OperationResult.failure(
|
return OperationResult.failure(_errorMessage(failure));
|
||||||
_errorMessage(failure),
|
|
||||||
errorCode: failure is ApiException ? failure.code : null,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
_likingCommentIds.remove(comment.id);
|
_likingCommentIds.remove(comment.id);
|
||||||
_notify();
|
_notify();
|
||||||
@@ -286,10 +277,7 @@ class CommentController extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
return OperationResult.success(reportId);
|
return OperationResult.success(reportId);
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
return OperationResult.failure(
|
return OperationResult.failure(_errorMessage(failure));
|
||||||
_errorMessage(failure),
|
|
||||||
errorCode: failure is ApiException ? failure.code : null,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
import '../models/drama.dart';
|
import '../models/drama.dart';
|
||||||
import '../remote/api_client.dart';
|
|
||||||
import '../repositories/favorite_repository.dart';
|
import '../repositories/favorite_repository.dart';
|
||||||
|
|
||||||
/// 收藏状态:**以服务端为准**。
|
/// 收藏状态:**以服务端为准**。
|
||||||
@@ -25,7 +24,6 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
bool hasMore = false;
|
bool hasMore = false;
|
||||||
String? error;
|
String? error;
|
||||||
String? loadMoreError;
|
String? loadMoreError;
|
||||||
int? lastErrorCode;
|
|
||||||
int _pageIndex = 0;
|
int _pageIndex = 0;
|
||||||
int _requestSeq = 0;
|
int _requestSeq = 0;
|
||||||
bool _disposed = false;
|
bool _disposed = false;
|
||||||
@@ -34,17 +32,6 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
|
|
||||||
bool isSaved(String dramaId) => _saved.contains(dramaId);
|
bool isSaved(String dramaId) => _saved.contains(dramaId);
|
||||||
|
|
||||||
/// 用统计快照校准收藏状态;已有列表卡片结构不因一次状态同步而改动。
|
|
||||||
void applyServerState(String dramaId, {required bool saved}) {
|
|
||||||
final changed = _saved.contains(dramaId) != saved;
|
|
||||||
if (saved) {
|
|
||||||
_saved.add(dramaId);
|
|
||||||
} else {
|
|
||||||
_saved.remove(dramaId);
|
|
||||||
}
|
|
||||||
if (changed) notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
void notify() {
|
void notify() {
|
||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
}
|
}
|
||||||
@@ -114,12 +101,11 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 每次切换都以接口状态为准;匿名请求由设备号归属。
|
/// 未登录时不要调用(服务端要求登录态)。
|
||||||
///
|
///
|
||||||
/// [card] 是当前剧的卡片(播放页/详情页手上就有):收藏成功时直接放进列表,
|
/// [card] 是当前剧的卡片(播放页/详情页手上就有):收藏成功时直接放进列表,
|
||||||
/// 这样"收藏完打开我的收藏"能立刻看到,不必等下一次整表刷新。
|
/// 这样"收藏完打开我的收藏"能立刻看到,不必等下一次整表刷新。
|
||||||
Future<bool> toggle(String dramaId, {Drama? card}) async {
|
Future<bool> toggle(String dramaId, {Drama? card}) async {
|
||||||
lastErrorCode = null;
|
|
||||||
final wasSaved = _saved.contains(dramaId);
|
final wasSaved = _saved.contains(dramaId);
|
||||||
final previousCards = cards;
|
final previousCards = cards;
|
||||||
final previousTotal = total;
|
final previousTotal = total;
|
||||||
@@ -160,7 +146,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
notify();
|
notify();
|
||||||
return true;
|
return true;
|
||||||
} catch (failure) {
|
} catch (_) {
|
||||||
// 回滚
|
// 回滚
|
||||||
cards = previousCards;
|
cards = previousCards;
|
||||||
total = previousTotal;
|
total = previousTotal;
|
||||||
@@ -171,7 +157,6 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
_saved.remove(dramaId);
|
_saved.remove(dramaId);
|
||||||
}
|
}
|
||||||
notify();
|
notify();
|
||||||
if (failure is ApiException) lastErrorCode = failure.code;
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,24 +40,6 @@ class InteractionController extends ChangeNotifier {
|
|||||||
/// 该集服务端最新点赞数。
|
/// 该集服务端最新点赞数。
|
||||||
int? episodeLikeCount(String episodeId) => _episodeLikeCounts[episodeId];
|
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) =>
|
Future<OperationResult<LikeToggleResult>> toggleDramaLike(String dramaId) =>
|
||||||
_toggleLike(
|
_toggleLike(
|
||||||
@@ -115,10 +97,7 @@ class InteractionController extends ChangeNotifier {
|
|||||||
} else {
|
} else {
|
||||||
likedIds.remove(id);
|
likedIds.remove(id);
|
||||||
}
|
}
|
||||||
return OperationResult.failure(
|
return OperationResult.failure(_errorMessage(failure));
|
||||||
_errorMessage(failure),
|
|
||||||
errorCode: failure is ApiException ? failure.code : null,
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
busyIds.remove(id);
|
busyIds.remove(id);
|
||||||
_notify();
|
_notify();
|
||||||
@@ -142,10 +121,7 @@ class InteractionController extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
return OperationResult.success(reportId);
|
return OperationResult.success(reportId);
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
return OperationResult.failure(
|
return OperationResult.failure(_errorMessage(failure));
|
||||||
_errorMessage(failure),
|
|
||||||
errorCode: failure is ApiException ? failure.code : null,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
// 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,9 +7,6 @@ import '../models/drama.dart';
|
|||||||
import '../models/player_port.dart';
|
import '../models/player_port.dart';
|
||||||
import 'video_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: 200);
|
||||||
|
|
||||||
@@ -17,9 +14,37 @@ typedef PlayerFactory = PlayerPort Function(Episode episode);
|
|||||||
typedef PlayerPreparation =
|
typedef PlayerPreparation =
|
||||||
Future<void> Function(Episode episode, PlayerPort player);
|
Future<void> Function(Episode episode, PlayerPort player);
|
||||||
|
|
||||||
enum PlaybackSessionOwner { home, 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();
|
||||||
|
|
||||||
/// Owns current plus previous/next frames; allocation stays serialized.
|
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.
|
||||||
class PlaybackSession extends ChangeNotifier {
|
class PlaybackSession extends ChangeNotifier {
|
||||||
PlaybackSession({
|
PlaybackSession({
|
||||||
required this.episodes,
|
required this.episodes,
|
||||||
@@ -29,8 +54,6 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
this.activate,
|
this.activate,
|
||||||
PlaybackCoordinator? coordinator,
|
PlaybackCoordinator? coordinator,
|
||||||
this.waitForFrame,
|
this.waitForFrame,
|
||||||
this.owner = PlaybackSessionOwner.player,
|
|
||||||
this.dramaIdAt,
|
|
||||||
}) : _coordinator = coordinator ?? PlaybackCoordinator();
|
}) : _coordinator = coordinator ?? PlaybackCoordinator();
|
||||||
|
|
||||||
final List<Episode> episodes;
|
final List<Episode> episodes;
|
||||||
@@ -43,20 +66,16 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
/// Runs only when a slot becomes current (e.g. progress listeners).
|
/// Runs only when a slot becomes current (e.g. progress listeners).
|
||||||
final PlayerPreparation? activate;
|
final PlayerPreparation? activate;
|
||||||
final Future<void> Function()? waitForFrame;
|
final Future<void> Function()? waitForFrame;
|
||||||
final PlaybackSessionOwner owner;
|
|
||||||
final String? Function(int index)? dramaIdAt;
|
|
||||||
final PlaybackCoordinator _coordinator;
|
final PlaybackCoordinator _coordinator;
|
||||||
final Set<_PlayerSlot> _live = {};
|
final Set<_PlayerSlot> _live = {};
|
||||||
_PlayerSlot? _active;
|
_PlayerSlot? _active;
|
||||||
_PlayerSlot? _next;
|
_PlayerSlot? _next;
|
||||||
_PlayerSlot? _previous;
|
|
||||||
_PlayerSlot? _handoff;
|
_PlayerSlot? _handoff;
|
||||||
Future<void> _operations = Future<void>.value();
|
Future<void> _operations = Future<void>.value();
|
||||||
Future<void> _preloadTask = Future<void>.value();
|
Future<void> _preloadTask = Future<void>.value();
|
||||||
int _generation = 0;
|
int _generation = 0;
|
||||||
int _currentIndex = 0;
|
int _currentIndex = 0;
|
||||||
int? _nextIndex;
|
int? _nextIndex;
|
||||||
int? _previousIndex;
|
|
||||||
bool _selected = false;
|
bool _selected = false;
|
||||||
bool _loading = false;
|
bool _loading = false;
|
||||||
bool _closed = false;
|
bool _closed = false;
|
||||||
@@ -84,18 +103,9 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
bool get canAutoAdvance => _mayPlay && !_loading && active != null;
|
bool get canAutoAdvance => _mayPlay && !_loading && active != null;
|
||||||
bool get isLocked => !canPlay(currentEpisode);
|
bool get isLocked => !canPlay(currentEpisode);
|
||||||
String? get error => _error;
|
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.
|
// Includes initialization and asynchronous disposal, until native release ends.
|
||||||
int get livePlayerCount => _live.length;
|
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 preloadedIndex => _next?.prepared == true ? _next?.index : null;
|
||||||
int? get previousPreloadedIndex =>
|
|
||||||
_previous?.prepared == true ? _previous?.index : null;
|
|
||||||
Future<void> get playbackSettled => _operations;
|
Future<void> get playbackSettled => _operations;
|
||||||
Future<void> get preloadSettled => _preloadTask;
|
Future<void> get preloadSettled => _preloadTask;
|
||||||
|
|
||||||
@@ -110,7 +120,7 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
/// during a swipe without starting audio or registering history listeners.
|
/// during a swipe without starting audio or registering history listeners.
|
||||||
PlayerPort? preparedPlayerAt(int index) {
|
PlayerPort? preparedPlayerAt(int index) {
|
||||||
if (_closed) return null;
|
if (_closed) return null;
|
||||||
for (final slot in [_active, _next, _previous]) {
|
for (final slot in [_active, _next]) {
|
||||||
if (slot == null ||
|
if (slot == null ||
|
||||||
slot.retiring ||
|
slot.retiring ||
|
||||||
slot.index != index ||
|
slot.index != index ||
|
||||||
@@ -122,41 +132,34 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 清晰度切换时盖住黑帧的旧播放器。只在仍由会话持有时交给界面。
|
||||||
|
PlayerPort? handoffAt(int index) {
|
||||||
|
final slot = _handoff;
|
||||||
|
if (_closed || slot == null || slot.retiring || slot.index != index) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return slot.player;
|
||||||
|
}
|
||||||
|
|
||||||
/// 队列重排后把当前仍在播放的 slot 映射到新索引,不重新创建播放器。
|
/// 队列重排后把当前仍在播放的 slot 映射到新索引,不重新创建播放器。
|
||||||
void remapCurrentIndex(int index, {int? preloadIndex, int? previousIndex}) {
|
void remapCurrentIndex(int index, {int? preloadIndex}) {
|
||||||
if (_closed || index < 0 || index >= episodes.length) return;
|
if (_closed || index < 0 || index >= episodes.length) return;
|
||||||
final activeSlot = _active;
|
final activeSlot = _active;
|
||||||
if (activeSlot == null || activeSlot.index != _currentIndex) {
|
if (activeSlot == null || activeSlot.index != _currentIndex) {
|
||||||
_currentIndex = index;
|
_currentIndex = index;
|
||||||
_rememberNeighbors(preloadIndex, previousIndex);
|
_nextIndex = preloadIndex;
|
||||||
_notify();
|
_notify();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_generation++;
|
_generation++;
|
||||||
activeSlot.index = index;
|
activeSlot.index = index;
|
||||||
_currentIndex = index;
|
_currentIndex = index;
|
||||||
_rememberNeighbors(preloadIndex, previousIndex);
|
|
||||||
final staleNext = _next;
|
|
||||||
final stalePrevious = _previous;
|
|
||||||
_next = null;
|
|
||||||
_previous = null;
|
|
||||||
_notify();
|
|
||||||
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;
|
_nextIndex = preloadIndex;
|
||||||
_previousIndex = previousIndex;
|
final staleNext = _next;
|
||||||
|
_next = null;
|
||||||
|
_notify();
|
||||||
|
unawaited(_enqueue(() async => _retire(staleNext)));
|
||||||
|
if (_visible && !_overlayOpen) _schedulePreload();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _enqueue(Future<void> Function() operation) {
|
Future<void> _enqueue(Future<void> Function() operation) {
|
||||||
@@ -173,15 +176,8 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_PlayerSlot _create(int index) {
|
_PlayerSlot _create(int index) {
|
||||||
if (_live.length >= maxLivePlayers) {
|
if (_live.length >= 2) throw StateError('Playback resource limit reached');
|
||||||
throw StateError('Playback resource limit reached');
|
final slot = _PlayerSlot(index, factory(episodes[index]));
|
||||||
}
|
|
||||||
final slot = _PlayerSlot(
|
|
||||||
index,
|
|
||||||
factory(episodes[index]),
|
|
||||||
owner: owner,
|
|
||||||
dramaId: dramaIdAt?.call(index),
|
|
||||||
);
|
|
||||||
_live.add(slot);
|
_live.add(slot);
|
||||||
slot.ready = () async {
|
slot.ready = () async {
|
||||||
try {
|
try {
|
||||||
@@ -199,32 +195,12 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
return slot;
|
return slot;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _retire(
|
Future<void> _retire(_PlayerSlot? slot) async {
|
||||||
_PlayerSlot? slot, {
|
if (slot == null || !_live.contains(slot)) return;
|
||||||
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;
|
slot.retiring = true;
|
||||||
final cleared =
|
final cleared = _active == slot || _next == slot || _handoff == slot;
|
||||||
_active == slot ||
|
|
||||||
_next == slot ||
|
|
||||||
_previous == slot ||
|
|
||||||
_handoff == slot;
|
|
||||||
if (_active == slot) _active = null;
|
if (_active == slot) _active = null;
|
||||||
if (_next == slot) _next = null;
|
if (_next == slot) _next = null;
|
||||||
if (_previous == slot) _previous = null;
|
|
||||||
if (_handoff == slot) _handoff = null;
|
if (_handoff == slot) _handoff = null;
|
||||||
if (cleared) _notify();
|
if (cleared) _notify();
|
||||||
await waitForFrame?.call();
|
await waitForFrame?.call();
|
||||||
@@ -234,51 +210,22 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
} finally {
|
} finally {
|
||||||
await slot.player.dispose();
|
await slot.player.dispose();
|
||||||
_live.remove(slot);
|
_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
|
/// preloadIndex comes from the visible queue, so filtered categories and series
|
||||||
/// use exactly the same mechanism without warming an unrelated episode.
|
/// use exactly the same mechanism without warming an unrelated episode.
|
||||||
Future<void> select(
|
Future<void> select(int index, {int? preloadIndex}) async {
|
||||||
int index, {
|
|
||||||
int? preloadIndex,
|
|
||||||
int? previousIndex,
|
|
||||||
bool? userWantsPlay,
|
|
||||||
}) async {
|
|
||||||
if (_closed || index < 0 || index >= episodes.length) return;
|
if (_closed || index < 0 || index >= episodes.length) return;
|
||||||
if (kDebugMode) {
|
// 切到另一集时,上一集按下的暂停不跟着走:滑过去就应该自动播放。
|
||||||
debugPrint(
|
// 重复选中同一集(例如页面重新可见)不在这里恢复,尊重用户按下的暂停。
|
||||||
'[player-session] phase=select-enter session=${identityHashCode(this)} '
|
if (!_selected || index != _currentIndex) {
|
||||||
'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;
|
_userWantsPlay = true;
|
||||||
}
|
}
|
||||||
final request = ++_generation;
|
final request = ++_generation;
|
||||||
_selected = true;
|
_selected = true;
|
||||||
_currentIndex = index;
|
_currentIndex = index;
|
||||||
_rememberNeighbors(preloadIndex, previousIndex);
|
_nextIndex = preloadIndex;
|
||||||
_error = null;
|
_error = null;
|
||||||
if (!_visible) {
|
if (!_visible) {
|
||||||
_loading = false;
|
_loading = false;
|
||||||
@@ -303,7 +250,7 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
_PlayerSlot? target;
|
_PlayerSlot? target;
|
||||||
await _enqueue(() async {
|
await _enqueue(() async {
|
||||||
if (_closed || request != _generation) return;
|
if (_closed || request != _generation) return;
|
||||||
await _retire(_handoff, trigger: 'select-handoff');
|
await _retire(_handoff);
|
||||||
final old = _active;
|
final old = _active;
|
||||||
if (old != null &&
|
if (old != null &&
|
||||||
old.index == index &&
|
old.index == index &&
|
||||||
@@ -312,27 +259,20 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
target = old;
|
target = old;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (old != null) {
|
if (old != null) await old.player.pause();
|
||||||
await old.player.pause();
|
final warm = _next;
|
||||||
old.playing = false;
|
|
||||||
}
|
|
||||||
final warmNext = _next;
|
|
||||||
final warmPrevious = _previous;
|
|
||||||
_active = null;
|
_active = null;
|
||||||
_next = null;
|
_next = null;
|
||||||
_previous = null;
|
final hit = warm?.index == index && warm?.failure == null && !isLocked;
|
||||||
final warm =
|
if (hit) {
|
||||||
_usableWarm(this, warmNext, index) ??
|
|
||||||
_usableWarm(this, warmPrevious, index);
|
|
||||||
if (warm != null) {
|
|
||||||
warm.reusedWarm = true;
|
|
||||||
target = _active = warm;
|
target = _active = warm;
|
||||||
_loading = !warm.prepared;
|
_loading = !warm!.prepared;
|
||||||
_notify();
|
_notify();
|
||||||
// Start a ready successor before awaiting slow disposal of the old one.
|
// Start a ready successor before awaiting slow disposal of the old one.
|
||||||
if (warm.prepared) await _start(warm, request);
|
if (warm.prepared) await _start(warm, request);
|
||||||
}
|
}
|
||||||
await _parkNeighbors(this, old, warmNext, warmPrevious);
|
await _retire(old);
|
||||||
|
if (!hit) await _retire(warm);
|
||||||
if (_closed || request != _generation || isLocked) return;
|
if (_closed || request != _generation || isLocked) return;
|
||||||
if (target == null) {
|
if (target == null) {
|
||||||
target = _active = _create(index);
|
target = _active = _create(index);
|
||||||
@@ -345,7 +285,7 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
await slot.ready;
|
await slot.ready;
|
||||||
if (_closed || request != _generation || _active != slot) return;
|
if (_closed || request != _generation || _active != slot) return;
|
||||||
await _enqueue(() => _start(slot, request));
|
await _enqueue(() => _start(slot, request));
|
||||||
if (!_closed && request == _generation) _warmNeighbors(this);
|
if (!_closed && request == _generation) _schedulePreload();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 后台准备新片源,成功后再替换当前播放器。失败时原播放器保持不动。
|
/// 后台准备新片源,成功后再替换当前播放器。失败时原播放器保持不动。
|
||||||
@@ -374,11 +314,9 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
await _enqueue(() => _start(slot, request));
|
await _enqueue(() => _start(slot, request));
|
||||||
await Future<void>.delayed(_qualityHandoffHold);
|
await Future<void>.delayed(_qualityHandoffHold);
|
||||||
if (previous != null && _handoff == previous && _active == slot) {
|
if (previous != null && _handoff == previous && _active == slot) {
|
||||||
await _enqueue(
|
await _enqueue(() => _retire(previous));
|
||||||
() => _retire(previous, trigger: 'quality-handoff-complete'),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (!_closed && request == _generation) _warmNeighbors(this);
|
if (!_closed && request == _generation) _schedulePreload();
|
||||||
return _active == slot && slot.failure == null;
|
return _active == slot && slot.failure == null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -388,8 +326,8 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
if (_closed || request != _generation || _active == null) return;
|
if (_closed || request != _generation || _active == null) return;
|
||||||
final warm = _next;
|
final warm = _next;
|
||||||
_next = null;
|
_next = null;
|
||||||
await _retire(_handoff, trigger: 'replacement-handoff');
|
await _retire(_handoff);
|
||||||
await _retire(warm, trigger: 'replacement-next');
|
await _retire(warm);
|
||||||
if (_closed || request != _generation || _active == null) return;
|
if (_closed || request != _generation || _active == null) return;
|
||||||
try {
|
try {
|
||||||
created = _create(index);
|
created = _create(index);
|
||||||
@@ -416,9 +354,7 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
|
|
||||||
Future<void> _dropReplacement(_PlayerSlot slot) {
|
Future<void> _dropReplacement(_PlayerSlot slot) {
|
||||||
return _enqueue(() async {
|
return _enqueue(() async {
|
||||||
if (_live.contains(slot)) {
|
if (_live.contains(slot)) await _retire(slot);
|
||||||
await _retire(slot, trigger: 'replacement-drop');
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -433,10 +369,7 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
_handoff = previous;
|
_handoff = previous;
|
||||||
_active = slot;
|
_active = slot;
|
||||||
shown = true;
|
shown = true;
|
||||||
if (previous != null) {
|
if (previous != null) await previous!.player.pause();
|
||||||
await previous!.player.pause();
|
|
||||||
previous!.playing = false;
|
|
||||||
}
|
|
||||||
_notify();
|
_notify();
|
||||||
});
|
});
|
||||||
if (!shown || _active != slot) return null;
|
if (!shown || _active != slot) return null;
|
||||||
@@ -480,22 +413,6 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
Future<void> _applyPlayback(_PlayerSlot slot) async {
|
Future<void> _applyPlayback(_PlayerSlot slot) async {
|
||||||
if (_closed || _active != slot || !slot.activated) return;
|
if (_closed || _active != slot || !slot.activated) return;
|
||||||
final shouldPlay = _mayPlay && slot.index == _currentIndex && !isLocked;
|
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 == slot.playing) return;
|
||||||
if (shouldPlay) {
|
if (shouldPlay) {
|
||||||
await slot.player.play();
|
await slot.player.play();
|
||||||
@@ -503,42 +420,96 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
await slot.player.pause();
|
await slot.player.pause();
|
||||||
}
|
}
|
||||||
slot.playing = shouldPlay;
|
slot.playing = shouldPlay;
|
||||||
if (kDebugMode) {
|
}
|
||||||
debugPrint(
|
|
||||||
'[player-session] phase=apply-playback-result '
|
void _schedulePreload() {
|
||||||
'session=${identityHashCode(this)} index=${slot.index} '
|
final request = _generation;
|
||||||
'shouldPlay=$shouldPlay '
|
final index = _nextIndex;
|
||||||
'isPlaying=${video?.controller.value.isPlaying ?? '-'} '
|
_preloadTask = () async {
|
||||||
'slotPlaying=${slot.playing}',
|
_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();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _syncPlayback() {
|
void _syncPlayback() {
|
||||||
if (_closed) return;
|
if (_closed) return;
|
||||||
if (_visible && _selected && active == null) {
|
if (_visible && _selected && active == null) {
|
||||||
unawaited(
|
unawaited(select(_currentIndex, preloadIndex: _nextIndex));
|
||||||
select(
|
|
||||||
_currentIndex,
|
|
||||||
preloadIndex: _nextIndex,
|
|
||||||
previousIndex: _previousIndex,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final slot = _active;
|
final slot = _active;
|
||||||
if (slot != null) unawaited(_enqueue(() => _applyPlayback(slot)));
|
if (slot != null) unawaited(_enqueue(() => _applyPlayback(slot)));
|
||||||
if (_visible && !_overlayOpen && !_loading) _warmNeighbors(this);
|
if (_visible && !_overlayOpen && !_loading) _schedulePreload();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _releasePlayers() {
|
Future<void> _releasePlayers() {
|
||||||
_generation++;
|
_generation++;
|
||||||
return _enqueue(() async {
|
return _enqueue(() async {
|
||||||
_active = _next = _previous = _handoff = null;
|
_active = _next = _handoff = null;
|
||||||
_loading = false;
|
_loading = false;
|
||||||
_notify();
|
_notify();
|
||||||
for (final slot in _live.toList()) {
|
for (final slot in _live.toList()) {
|
||||||
await _retire(slot, trigger: 'session-release-all');
|
await _retire(slot);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -547,23 +518,6 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
if (!_closed) notifyListeners();
|
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 {
|
Future<void> close() async {
|
||||||
if (_closed) return;
|
if (_closed) return;
|
||||||
_closed = true;
|
_closed = true;
|
||||||
@@ -574,27 +528,13 @@ class PlaybackSession extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _PlayerSlot {
|
class _PlayerSlot {
|
||||||
_PlayerSlot(
|
_PlayerSlot(this.index, this.player);
|
||||||
this.index,
|
|
||||||
this.player, {
|
|
||||||
required this.owner,
|
|
||||||
required this.dramaId,
|
|
||||||
});
|
|
||||||
int index;
|
int index;
|
||||||
final PlayerPort player;
|
final PlayerPort player;
|
||||||
final PlaybackSessionOwner owner;
|
|
||||||
final String? dramaId;
|
|
||||||
late final Future<void> ready;
|
late final Future<void> ready;
|
||||||
bool prepared = false;
|
bool prepared = false;
|
||||||
bool activated = false;
|
bool activated = false;
|
||||||
bool playing = false;
|
bool playing = false;
|
||||||
bool retiring = false;
|
bool retiring = false;
|
||||||
bool reusedWarm = false;
|
|
||||||
Object? failure;
|
Object? failure;
|
||||||
}
|
}
|
||||||
|
|
||||||
String _playerIdentity(PlayerPort player) {
|
|
||||||
return player is VideoPlayerPort
|
|
||||||
? '${identityHashCode(player.controller)}'
|
|
||||||
: '${identityHashCode(player)}';
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
// 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
// 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';
|
import 'sprite_thumbnail_asset_loader.dart';
|
||||||
|
|
||||||
const Duration spriteVttCacheTtl = Duration(minutes: 10);
|
const Duration spriteVttCacheTtl = Duration(minutes: 10);
|
||||||
const int spriteImageCacheCapacity = 1;
|
const int spriteImageCacheCapacity = 2;
|
||||||
|
|
||||||
/// 单个 VTT cue 对应的 sprite 裁剪区域。
|
/// 单个 VTT cue 对应的 sprite 裁剪区域。
|
||||||
class SpriteThumbnailCue {
|
class SpriteThumbnailCue {
|
||||||
@@ -132,36 +132,36 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
SpriteThumbnailAxisService({
|
SpriteThumbnailAxisService({
|
||||||
SpriteThumbnailAssetLoader? loader,
|
SpriteThumbnailAssetLoader? loader,
|
||||||
this.cacheTtl = spriteVttCacheTtl,
|
this.cacheTtl = spriteVttCacheTtl,
|
||||||
this.spriteCacheCapacity = spriteImageCacheCapacity,
|
|
||||||
DateTime Function()? now,
|
DateTime Function()? now,
|
||||||
}) : _loader = loader ?? DioSpriteThumbnailAssetLoader(),
|
}) : _loader = loader ?? DioSpriteThumbnailAssetLoader(),
|
||||||
_now = now ?? DateTime.now;
|
_now = now ?? DateTime.now;
|
||||||
|
|
||||||
final SpriteThumbnailAssetLoader _loader;
|
final SpriteThumbnailAssetLoader _loader;
|
||||||
final Duration cacheTtl;
|
final Duration cacheTtl;
|
||||||
final int spriteCacheCapacity;
|
|
||||||
final DateTime Function() _now;
|
final DateTime Function() _now;
|
||||||
final Map<String, _CachedAxis> _axisCache = {};
|
final Map<String, _CachedAxis> _axisCache = {};
|
||||||
final Map<String, Future<SpriteThumbnailAxis>> _axisRequests = {};
|
final Map<String, Future<SpriteThumbnailAxis>> _axisRequests = {};
|
||||||
final LinkedHashMap<String, _CachedSprite> _spriteCache = LinkedHashMap();
|
final LinkedHashMap<String, _CachedSprite> _spriteCache = LinkedHashMap();
|
||||||
final Map<String, Future<_CachedSprite?>> _spriteRequests = {};
|
final Map<String, Future<_CachedSprite?>> _spriteRequests = {};
|
||||||
final Set<String> _failedSprites = {};
|
final Set<String> _failedSprites = {};
|
||||||
|
String? _activeAxisUrl;
|
||||||
|
int _axisGeneration = 0;
|
||||||
bool _disposed = false;
|
bool _disposed = false;
|
||||||
|
|
||||||
|
@visibleForTesting
|
||||||
int get spriteCacheSize => _spriteCache.length;
|
int get spriteCacheSize => _spriteCache.length;
|
||||||
|
|
||||||
@visibleForTesting
|
@visibleForTesting
|
||||||
List<String> get spriteCacheKeys => _spriteCache.keys
|
List<String> get spriteCacheKeys => _spriteCache.keys.toList();
|
||||||
.map((url) => Uri.tryParse(url)?.pathSegments.lastOrNull ?? url)
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
/// 播放器就绪时预取当前 cue;容量大于 1 时顺带预取相邻 sprite。
|
/// 播放器就绪时预取当前 cue 与相邻 sprite,拖动帧不触发网络或解码。
|
||||||
@override
|
@override
|
||||||
Future<void> prepareAt(String? thumbnailsUrl, Duration position) async {
|
Future<void> prepareAt(String? thumbnailsUrl, Duration position) async {
|
||||||
final url = _normalizeUrl(thumbnailsUrl);
|
final url = _normalizeUrl(thumbnailsUrl);
|
||||||
if (_disposed || url == null) return;
|
if (_disposed || url == null) return;
|
||||||
|
_activateAxis(url);
|
||||||
final axis = await _loadAxis(url);
|
final axis = await _loadAxis(url);
|
||||||
if (_disposed) return;
|
if (_disposed || _activeAxisUrl != url) return;
|
||||||
for (final cue in _prefetchCues(axis, position)) {
|
for (final cue in _prefetchCues(axis, position)) {
|
||||||
await _ensureSprite(axis, cue);
|
await _ensureSprite(axis, cue);
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
@override
|
@override
|
||||||
bool hasAxis(String? thumbnailsUrl) {
|
bool hasAxis(String? thumbnailsUrl) {
|
||||||
final url = _normalizeUrl(thumbnailsUrl);
|
final url = _normalizeUrl(thumbnailsUrl);
|
||||||
if (url == null) return false;
|
if (url == null || url != _activeAxisUrl) return false;
|
||||||
return _readAxis(url) != null;
|
return _readAxis(url) != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,14 +180,12 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
Duration position,
|
Duration position,
|
||||||
) {
|
) {
|
||||||
final url = _normalizeUrl(thumbnailsUrl);
|
final url = _normalizeUrl(thumbnailsUrl);
|
||||||
if (url == null) return null;
|
if (url == null || url != _activeAxisUrl) return null;
|
||||||
final axis = _readAxis(url);
|
final axis = _readAxis(url);
|
||||||
if (axis == null) return null;
|
if (axis == null) return null;
|
||||||
final cue = selectSpriteThumbnailCue(axis.cues, position);
|
final cue = selectSpriteThumbnailCue(axis.cues, position);
|
||||||
if (cue == null) return null;
|
if (cue == null) return null;
|
||||||
final cached = _readSprite(
|
final cached = _readSprite(cue.spriteFile);
|
||||||
axis.resolveSpriteUri(cue.spriteFile).toString(),
|
|
||||||
);
|
|
||||||
if (cached == null) return null;
|
if (cached == null) return null;
|
||||||
final sourceRect = _scaledSourceRect(cached, cue.sourceRect);
|
final sourceRect = _scaledSourceRect(cached, cue.sourceRect);
|
||||||
if (sourceRect == null) return null;
|
if (sourceRect == null) return null;
|
||||||
@@ -208,6 +206,13 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _activateAxis(String url) {
|
||||||
|
if (_activeAxisUrl == url) return;
|
||||||
|
_activeAxisUrl = url;
|
||||||
|
_axisGeneration++;
|
||||||
|
_clearSprites();
|
||||||
|
}
|
||||||
|
|
||||||
Future<SpriteThumbnailAxis> _loadAxis(String url) {
|
Future<SpriteThumbnailAxis> _loadAxis(String url) {
|
||||||
final cached = _readAxis(url);
|
final cached = _readAxis(url);
|
||||||
if (cached != null) return Future.value(cached);
|
if (cached != null) return Future.value(cached);
|
||||||
@@ -234,6 +239,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
} on SpriteThumbnailForbiddenException {
|
} on SpriteThumbnailForbiddenException {
|
||||||
if (_disposed) return SpriteThumbnailAxis.empty(url);
|
if (_disposed) return SpriteThumbnailAxis.empty(url);
|
||||||
_axisCache.remove(url);
|
_axisCache.remove(url);
|
||||||
|
if (_activeAxisUrl == url) _clearSprites();
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -268,7 +274,6 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
if (current == null) return const [];
|
if (current == null) return const [];
|
||||||
final index = axis.cues.indexOf(current);
|
final index = axis.cues.indexOf(current);
|
||||||
final candidates = <SpriteThumbnailCue>[current];
|
final candidates = <SpriteThumbnailCue>[current];
|
||||||
if (spriteCacheCapacity <= 1) return candidates;
|
|
||||||
for (final direction in const [1, -1]) {
|
for (final direction in const [1, -1]) {
|
||||||
for (var step = 1; step < axis.cues.length; step++) {
|
for (var step = 1; step < axis.cues.length; step++) {
|
||||||
final neighborIndex = index + direction * step;
|
final neighborIndex = index + direction * step;
|
||||||
@@ -288,23 +293,23 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
SpriteThumbnailAxis axis,
|
SpriteThumbnailAxis axis,
|
||||||
SpriteThumbnailCue cue,
|
SpriteThumbnailCue cue,
|
||||||
) {
|
) {
|
||||||
final spriteUrl = axis.resolveSpriteUri(cue.spriteFile).toString();
|
final cached = _readSprite(cue.spriteFile);
|
||||||
final cached = _readSprite(spriteUrl);
|
|
||||||
if (cached != null) return Future.value(cached);
|
if (cached != null) return Future.value(cached);
|
||||||
if (_failedSprites.contains(spriteUrl)) return Future.value();
|
if (_failedSprites.contains(cue.spriteFile)) return Future.value();
|
||||||
final existing = _spriteRequests[spriteUrl];
|
final existing = _spriteRequests[cue.spriteFile];
|
||||||
if (existing != null) return existing;
|
if (existing != null) return existing;
|
||||||
final request = _loadSprite(axis, cue, spriteUrl);
|
final generation = _axisGeneration;
|
||||||
_spriteRequests[spriteUrl] = request;
|
final request = _loadSprite(axis, cue, generation);
|
||||||
|
_spriteRequests[cue.spriteFile] = request;
|
||||||
return request.whenComplete(() {
|
return request.whenComplete(() {
|
||||||
_spriteRequests.remove(spriteUrl);
|
_spriteRequests.remove(cue.spriteFile);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<_CachedSprite?> _loadSprite(
|
Future<_CachedSprite?> _loadSprite(
|
||||||
SpriteThumbnailAxis axis,
|
SpriteThumbnailAxis axis,
|
||||||
SpriteThumbnailCue cue,
|
SpriteThumbnailCue cue,
|
||||||
String spriteUrl,
|
int generation,
|
||||||
) async {
|
) async {
|
||||||
SpriteThumbnailDecodedImage? decoded;
|
SpriteThumbnailDecodedImage? decoded;
|
||||||
try {
|
try {
|
||||||
@@ -313,16 +318,16 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
decoded = null;
|
decoded = null;
|
||||||
}
|
}
|
||||||
if (decoded == null) {
|
if (decoded == null) {
|
||||||
_failedSprites.add(spriteUrl);
|
_failedSprites.add(cue.spriteFile);
|
||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (_disposed) {
|
if (_disposed || generation != _axisGeneration) {
|
||||||
decoded.image.dispose();
|
decoded.image.dispose();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
final cached = _CachedSprite(decoded);
|
final cached = _CachedSprite(decoded);
|
||||||
_putSprite(spriteUrl, cached);
|
_putSprite(cue.spriteFile, cached);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
@@ -337,7 +342,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
void _putSprite(String key, _CachedSprite value) {
|
void _putSprite(String key, _CachedSprite value) {
|
||||||
_spriteCache.remove(key)?.decoded.image.dispose();
|
_spriteCache.remove(key)?.decoded.image.dispose();
|
||||||
_spriteCache[key] = value;
|
_spriteCache[key] = value;
|
||||||
while (_spriteCache.length > spriteCacheCapacity) {
|
while (_spriteCache.length > spriteImageCacheCapacity) {
|
||||||
final oldest = _spriteCache.remove(_spriteCache.keys.first);
|
final oldest = _spriteCache.remove(_spriteCache.keys.first);
|
||||||
oldest?.decoded.image.dispose();
|
oldest?.decoded.image.dispose();
|
||||||
}
|
}
|
||||||
@@ -373,6 +378,8 @@ class SpriteThumbnailAxisService extends ChangeNotifier
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _clearAll() {
|
void _clearAll() {
|
||||||
|
_axisGeneration++;
|
||||||
|
_activeAxisUrl = null;
|
||||||
_axisCache.clear();
|
_axisCache.clear();
|
||||||
_axisRequests.clear();
|
_axisRequests.clear();
|
||||||
_clearSprites();
|
_clearSprites();
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ String localizedDramaTitle(AppLocalizations l10n, Drama drama) =>
|
|||||||
'the-signal-demo' => l10n.dramaSignalTitle,
|
'the-signal-demo' => l10n.dramaSignalTitle,
|
||||||
'city-lights-demo' => l10n.dramaCityTitle,
|
'city-lights-demo' => l10n.dramaCityTitle,
|
||||||
'vengeance-demo' => l10n.dramaVengeanceTitle,
|
'vengeance-demo' => l10n.dramaVengeanceTitle,
|
||||||
_ => drama.localizedTitle(l10n.localeName.split(RegExp(r'[_-]')).first),
|
_ => drama.title,
|
||||||
};
|
};
|
||||||
|
|
||||||
String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
|
String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
|
||||||
@@ -16,7 +16,7 @@ String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
|
|||||||
'the-signal-demo' => l10n.dramaSignalSynopsis,
|
'the-signal-demo' => l10n.dramaSignalSynopsis,
|
||||||
'city-lights-demo' => l10n.dramaCitySynopsis,
|
'city-lights-demo' => l10n.dramaCitySynopsis,
|
||||||
'vengeance-demo' => l10n.dramaVengeanceSynopsis,
|
'vengeance-demo' => l10n.dramaVengeanceSynopsis,
|
||||||
_ => drama.localizedSynopsis(l10n.localeName.split(RegExp(r'[_-]')).first),
|
_ => drama.synopsis,
|
||||||
};
|
};
|
||||||
|
|
||||||
String localizedEpisodeTitle(AppLocalizations l10n, int number) =>
|
String localizedEpisodeTitle(AppLocalizations l10n, int number) =>
|
||||||
|
|||||||
@@ -4,16 +4,14 @@ import 'package:flutter/widgets.dart';
|
|||||||
|
|
||||||
/// 无位移的短促淡入转场。
|
/// 无位移的短促淡入转场。
|
||||||
class FadePageRoute<T> extends PageRouteBuilder<T> {
|
class FadePageRoute<T> extends PageRouteBuilder<T> {
|
||||||
FadePageRoute({
|
FadePageRoute({required WidgetBuilder builder, super.settings})
|
||||||
required WidgetBuilder builder,
|
: super(
|
||||||
super.settings,
|
transitionDuration: const Duration(milliseconds: 220),
|
||||||
super.transitionDuration = const Duration(milliseconds: 220),
|
reverseTransitionDuration: const Duration(milliseconds: 180),
|
||||||
super.reverseTransitionDuration = const Duration(milliseconds: 180),
|
pageBuilder: (context, _, _) => builder(context),
|
||||||
}) : super(
|
transitionsBuilder: (context, animation, _, child) => FadeTransition(
|
||||||
pageBuilder: (context, _, _) => builder(context),
|
opacity: CurvedAnimation(parent: animation, curve: Curves.easeOut),
|
||||||
transitionsBuilder: (context, animation, _, child) => FadeTransition(
|
child: child,
|
||||||
opacity: CurvedAnimation(parent: animation, curve: Curves.easeOut),
|
),
|
||||||
child: child,
|
);
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
// 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');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -112,9 +112,6 @@ abstract final class AppColors {
|
|||||||
static const textPrimary = Color(0xFFFFFFFF);
|
static const textPrimary = Color(0xFFFFFFFF);
|
||||||
static const textSecondary = Color(0xFFB0B0B0);
|
static const textSecondary = Color(0xFFB0B0B0);
|
||||||
static const textTertiary = Color(0xFF8E8E93);
|
static const textTertiary = Color(0xFF8E8E93);
|
||||||
|
|
||||||
/// 列表底部「没有更多了」这类弱提示。
|
|
||||||
static const textHint = Color(0xFF5C5C60);
|
|
||||||
static const textTabInactive = Color(0xFFB0B0B0);
|
static const textTabInactive = Color(0xFFB0B0B0);
|
||||||
static const textFilterIcon = Color(0xFF7A7A7E);
|
static const textFilterIcon = Color(0xFF7A7A7E);
|
||||||
static const searchResultMeta = Color(0xFF9E9E9E);
|
static const searchResultMeta = Color(0xFF9E9E9E);
|
||||||
|
|||||||
@@ -229,7 +229,7 @@ abstract final class AppDimens {
|
|||||||
static const double mineSectionLinkFont = 12;
|
static const double mineSectionLinkFont = 12;
|
||||||
static const double mineSectionGap = 20;
|
static const double mineSectionGap = 20;
|
||||||
static const double mineContinueCardWidth = 96;
|
static const double mineContinueCardWidth = 96;
|
||||||
static const double mineContinueRowHeight = 172;
|
static const double mineContinueRowHeight = 168;
|
||||||
static const double mineContinueTitleFont = 13;
|
static const double mineContinueTitleFont = 13;
|
||||||
static const double mineContinueMetaFont = 11;
|
static const double mineContinueMetaFont = 11;
|
||||||
static const double mineStatsValueFont = 18;
|
static const double mineStatsValueFont = 18;
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ Future<void> openAuthPage(BuildContext context, {bool signUpMode = false}) {
|
|||||||
|
|
||||||
/// 受限动作的登录闸:已登录返回 true;未登录弹底部提示并引导登录,返回 false。
|
/// 受限动作的登录闸:已登录返回 true;未登录弹底部提示并引导登录,返回 false。
|
||||||
///
|
///
|
||||||
/// 首页/发现/详情与非付费互动保持匿名可用;解锁、权益与消耗类动作走这里。
|
/// 首页/发现/详情保持匿名可看,只有收藏、点赞、评论这类"要对到具体账号"的动作才走这里。
|
||||||
Future<bool> ensureSignedIn(BuildContext context) async {
|
Future<bool> ensureSignedIn(BuildContext context) async {
|
||||||
final auth = context.read<AuthController>();
|
final auth = context.read<AuthController>();
|
||||||
if (auth.isSignedIn) return true;
|
if (auth.isSignedIn) return true;
|
||||||
@@ -76,7 +76,6 @@ Future<bool> ensureSignedIn(BuildContext context) async {
|
|||||||
|
|
||||||
if (go == true && context.mounted) {
|
if (go == true && context.mounted) {
|
||||||
await openAuthPage(context);
|
await openAuthPage(context);
|
||||||
if (context.mounted) return context.read<AuthController>().isSignedIn;
|
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,11 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'dart:math' as math;
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../theme/app_colors.dart';
|
import '../theme/app_colors.dart';
|
||||||
import '../theme/app_dimens.dart';
|
import '../theme/app_dimens.dart';
|
||||||
|
|
||||||
const Duration _shimmerPeriod = Duration(milliseconds: 1400);
|
class DramaGridSkeleton extends StatelessWidget {
|
||||||
const double _shimmerTravel = 2.4;
|
|
||||||
const double _shimmerStart = -1.2;
|
|
||||||
const double _subtitleWidthFactor = 0.62;
|
|
||||||
const Color _shimmerHighlight = Color(0x38FFFFFF);
|
|
||||||
|
|
||||||
/// 首页短剧网格的占位。行数至少铺满可视高度,并带一道扫光。
|
|
||||||
class DramaGridSkeleton extends StatefulWidget {
|
|
||||||
const DramaGridSkeleton({
|
const DramaGridSkeleton({
|
||||||
super.key,
|
super.key,
|
||||||
required this.columns,
|
required this.columns,
|
||||||
@@ -32,133 +23,61 @@ class DramaGridSkeleton extends StatefulWidget {
|
|||||||
final int itemCount;
|
final int itemCount;
|
||||||
final ScrollPhysics physics;
|
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return LayoutBuilder(
|
return LayoutBuilder(
|
||||||
builder: (context, constraints) {
|
builder: (context, constraints) {
|
||||||
final grid = _grid(constraints.maxWidth, constraints.maxHeight);
|
final itemWidth =
|
||||||
return AnimatedBuilder(
|
(constraints.maxWidth -
|
||||||
animation: _shimmer,
|
horizontalPadding * 2 -
|
||||||
builder: (context, child) => ShaderMask(
|
crossAxisSpacing * (columns - 1)) /
|
||||||
blendMode: BlendMode.srcATop,
|
columns;
|
||||||
shaderCallback: (bounds) => _shader(bounds),
|
final itemExtent =
|
||||||
child: child,
|
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(),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
child: grid,
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _grid(double width, double height) {
|
|
||||||
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),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
Shader _shader(Rect bounds) {
|
|
||||||
final shift = _shimmerStart + _shimmerTravel * _shimmer.value;
|
|
||||||
return LinearGradient(
|
|
||||||
begin: Alignment(shift, -0.3),
|
|
||||||
end: Alignment(shift + 1, 0.3),
|
|
||||||
colors: const [
|
|
||||||
AppColors.skeletonSurface,
|
|
||||||
_shimmerHighlight,
|
|
||||||
AppColors.skeletonSurface,
|
|
||||||
],
|
|
||||||
).createShader(bounds);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _SkeletonCard extends StatelessWidget {
|
|
||||||
const _SkeletonCard({required this.index});
|
|
||||||
|
|
||||||
final int index;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Column(
|
|
||||||
key: Key('drama-grid-skeleton-$index'),
|
|
||||||
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(),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
class _SkeletonBar extends StatelessWidget {
|
||||||
|
|||||||
@@ -8,27 +8,19 @@ import '../theme/app_colors.dart';
|
|||||||
import '../theme/app_dimens.dart';
|
import '../theme/app_dimens.dart';
|
||||||
import '../../l10n/app_localizations.dart';
|
import '../../l10n/app_localizations.dart';
|
||||||
|
|
||||||
/// 网络分页列表底部:加载中、失败重试、没有下一页。
|
/// 网络分页列表底部状态:仅保留加载圈与错误重试。
|
||||||
class PagedListFooter extends StatelessWidget {
|
class PagedListFooter extends StatelessWidget {
|
||||||
const PagedListFooter({
|
const PagedListFooter({
|
||||||
super.key,
|
super.key,
|
||||||
required this.loading,
|
required this.loading,
|
||||||
required this.onRetry,
|
required this.onRetry,
|
||||||
this.errorMessage,
|
this.errorMessage,
|
||||||
this.hasMore = true,
|
|
||||||
this.hasItems = false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final bool loading;
|
final bool loading;
|
||||||
final String? errorMessage;
|
final String? errorMessage;
|
||||||
final Future<void> Function() onRetry;
|
final Future<void> Function() onRetry;
|
||||||
|
|
||||||
/// 还有下一页时不显示结束文案。
|
|
||||||
final bool hasMore;
|
|
||||||
|
|
||||||
/// 列表为空时不显示「没有更多了」。
|
|
||||||
final bool hasItems;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
@@ -66,17 +58,6 @@ 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();
|
return const SizedBox.shrink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../l10n/app_localizations.dart';
|
|
||||||
import '../theme/app_colors.dart';
|
import '../theme/app_colors.dart';
|
||||||
import '../theme/app_dimens.dart';
|
import '../theme/app_dimens.dart';
|
||||||
|
|
||||||
@@ -72,14 +71,10 @@ class PagedLoadFooter extends StatelessWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
required this.loading,
|
required this.loading,
|
||||||
required this.loadMoreKey,
|
required this.loadMoreKey,
|
||||||
this.hasMore = true,
|
|
||||||
this.hasItems = false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final bool loading;
|
final bool loading;
|
||||||
final Key loadMoreKey;
|
final Key loadMoreKey;
|
||||||
final bool hasMore;
|
|
||||||
final bool hasItems;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -98,18 +93,6 @@ 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();
|
return const SizedBox.shrink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,24 +5,6 @@ import 'package:flutter/material.dart';
|
|||||||
import '../config/app_config.dart';
|
import '../config/app_config.dart';
|
||||||
import '../theme/app_colors.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 {
|
class RemoteImage extends StatelessWidget {
|
||||||
const RemoteImage(
|
const RemoteImage(
|
||||||
@@ -35,8 +17,6 @@ class RemoteImage extends StatelessWidget {
|
|||||||
this.fallbackIconKey,
|
this.fallbackIconKey,
|
||||||
this.fallbackAspectRatio,
|
this.fallbackAspectRatio,
|
||||||
this.fallbackColor = AppColors.raised,
|
this.fallbackColor = AppColors.raised,
|
||||||
this.decodeWidth,
|
|
||||||
this.decodeHeight,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final String path;
|
final String path;
|
||||||
@@ -47,56 +27,21 @@ class RemoteImage extends StatelessWidget {
|
|||||||
final Key? fallbackIconKey;
|
final Key? fallbackIconKey;
|
||||||
final double? fallbackAspectRatio;
|
final double? fallbackAspectRatio;
|
||||||
final Color fallbackColor;
|
final Color fallbackColor;
|
||||||
final int? decodeWidth;
|
|
||||||
final int? decodeHeight;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final url = AppConfig.mediaUrl(path);
|
final url = AppConfig.mediaUrl(path);
|
||||||
if (url.isEmpty) return _fallback(brand: showFallbackIcon);
|
if (url.isEmpty) return _fallback(brand: showFallbackIcon);
|
||||||
return LayoutBuilder(
|
return Image.network(
|
||||||
builder: (context, constraints) {
|
url,
|
||||||
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
|
width: width,
|
||||||
final layoutWidth = constraints.hasBoundedWidth
|
height: height,
|
||||||
? constraints.maxWidth
|
fit: fit,
|
||||||
: width;
|
gaplessPlayback: true,
|
||||||
final aspectRatio =
|
errorBuilder: (_, _, _) => _fallback(brand: showFallbackIcon),
|
||||||
fallbackAspectRatio != null &&
|
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
|
||||||
fallbackAspectRatio!.isFinite &&
|
if (wasSynchronouslyLoaded || frame != null) return child;
|
||||||
fallbackAspectRatio! > 0
|
return _fallback(brand: showFallbackIcon);
|
||||||
? fallbackAspectRatio
|
|
||||||
: null;
|
|
||||||
final inferredHeight = constraints.hasBoundedHeight
|
|
||||||
? constraints.maxHeight
|
|
||||||
: height ??
|
|
||||||
(layoutWidth != null && aspectRatio != null
|
|
||||||
? layoutWidth / aspectRatio
|
|
||||||
: null);
|
|
||||||
final cacheWidth =
|
|
||||||
decodeWidth ?? resolveImageDecodePixels(layoutWidth, pixelRatio);
|
|
||||||
final cacheHeight =
|
|
||||||
decodeHeight ??
|
|
||||||
(inferredHeight == null
|
|
||||||
? null
|
|
||||||
: resolveImageDecodePixels(inferredHeight, pixelRatio));
|
|
||||||
return Image.network(
|
|
||||||
url,
|
|
||||||
width: width,
|
|
||||||
height: height,
|
|
||||||
fit: fit,
|
|
||||||
cacheWidth: cacheWidth
|
|
||||||
.clamp(_minImageDecodePixels, _maxImageDecodePixels)
|
|
||||||
.toInt(),
|
|
||||||
cacheHeight: cacheHeight
|
|
||||||
?.clamp(_minImageDecodePixels, _maxImageDecodePixels)
|
|
||||||
.toInt(),
|
|
||||||
gaplessPlayback: true,
|
|
||||||
errorBuilder: (_, _, _) => _fallback(brand: showFallbackIcon),
|
|
||||||
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
|
|
||||||
if (wasSynchronouslyLoaded || frame != null) return child;
|
|
||||||
return _fallback(brand: showFallbackIcon);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -219,7 +219,6 @@
|
|||||||
"postComment": "Post",
|
"postComment": "Post",
|
||||||
"commentPostSuccess": "Comment posted",
|
"commentPostSuccess": "Comment posted",
|
||||||
"loadMore": "Load more",
|
"loadMore": "Load more",
|
||||||
"noMoreItems": "No more",
|
|
||||||
"commentsLoadFailed": "Comments could not be loaded.",
|
"commentsLoadFailed": "Comments could not be loaded.",
|
||||||
"commentPostFailed": "Could not post your comment.",
|
"commentPostFailed": "Could not post your comment.",
|
||||||
"delete": "Delete",
|
"delete": "Delete",
|
||||||
|
|||||||
@@ -193,7 +193,6 @@
|
|||||||
"postComment": "Kirim",
|
"postComment": "Kirim",
|
||||||
"commentPostSuccess": "Komentar terkirim",
|
"commentPostSuccess": "Komentar terkirim",
|
||||||
"loadMore": "Muat lebih banyak",
|
"loadMore": "Muat lebih banyak",
|
||||||
"noMoreItems": "Tidak ada lagi",
|
|
||||||
"commentsLoadFailed": "Komentar tidak dapat dimuat.",
|
"commentsLoadFailed": "Komentar tidak dapat dimuat.",
|
||||||
"commentPostFailed": "Komentar tidak dapat dikirim.",
|
"commentPostFailed": "Komentar tidak dapat dikirim.",
|
||||||
"delete": "Hapus",
|
"delete": "Hapus",
|
||||||
|
|||||||
@@ -994,12 +994,6 @@ abstract class AppLocalizations {
|
|||||||
/// **'Load more'**
|
/// **'Load more'**
|
||||||
String get loadMore;
|
String get loadMore;
|
||||||
|
|
||||||
/// No description provided for @noMoreItems.
|
|
||||||
///
|
|
||||||
/// In en, this message translates to:
|
|
||||||
/// **'No more'**
|
|
||||||
String get noMoreItems;
|
|
||||||
|
|
||||||
/// No description provided for @commentsLoadFailed.
|
/// No description provided for @commentsLoadFailed.
|
||||||
///
|
///
|
||||||
/// In en, this message translates to:
|
/// In en, this message translates to:
|
||||||
|
|||||||
@@ -486,9 +486,6 @@ class AppLocalizationsEn extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get loadMore => 'Load more';
|
String get loadMore => 'Load more';
|
||||||
|
|
||||||
@override
|
|
||||||
String get noMoreItems => 'No more';
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String get commentsLoadFailed => 'Comments could not be loaded.';
|
String get commentsLoadFailed => 'Comments could not be loaded.';
|
||||||
|
|
||||||
|
|||||||
@@ -487,9 +487,6 @@ class AppLocalizationsId extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get loadMore => 'Muat lebih banyak';
|
String get loadMore => 'Muat lebih banyak';
|
||||||
|
|
||||||
@override
|
|
||||||
String get noMoreItems => 'Tidak ada lagi';
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String get commentsLoadFailed => 'Komentar tidak dapat dimuat.';
|
String get commentsLoadFailed => 'Komentar tidak dapat dimuat.';
|
||||||
|
|
||||||
|
|||||||
@@ -481,9 +481,6 @@ class AppLocalizationsZh extends AppLocalizations {
|
|||||||
@override
|
@override
|
||||||
String get loadMore => '加载更多';
|
String get loadMore => '加载更多';
|
||||||
|
|
||||||
@override
|
|
||||||
String get noMoreItems => '没有更多了';
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String get commentsLoadFailed => '评论加载失败,请重试。';
|
String get commentsLoadFailed => '评论加载失败,请重试。';
|
||||||
|
|
||||||
|
|||||||
@@ -193,7 +193,6 @@
|
|||||||
"postComment": "发布",
|
"postComment": "发布",
|
||||||
"commentPostSuccess": "发表成功",
|
"commentPostSuccess": "发表成功",
|
||||||
"loadMore": "加载更多",
|
"loadMore": "加载更多",
|
||||||
"noMoreItems": "没有更多了",
|
|
||||||
"commentsLoadFailed": "评论加载失败,请重试。",
|
"commentsLoadFailed": "评论加载失败,请重试。",
|
||||||
"commentPostFailed": "评论发布失败,请重试。",
|
"commentPostFailed": "评论发布失败,请重试。",
|
||||||
"delete": "删除",
|
"delete": "删除",
|
||||||
|
|||||||
+1
-5
@@ -2,21 +2,17 @@
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
import 'app.dart';
|
import 'app.dart';
|
||||||
import 'core/config/app_config.dart';
|
import 'core/config/app_config.dart';
|
||||||
import 'core/config/server_endpoint.dart';
|
import 'core/config/server_endpoint.dart';
|
||||||
import 'core/platform/wireless_data_prompt.dart';
|
|
||||||
|
|
||||||
Future<void> main() async {
|
Future<void> main() async {
|
||||||
WidgetsFlutterBinding.ensureInitialized();
|
WidgetsFlutterBinding.ensureInitialized();
|
||||||
await ServerEndpoint.load();
|
await ServerEndpoint.load();
|
||||||
AppConfig.ready = WirelessDataPrompt.awaitDecision(
|
AppConfig.ready = AppConfig.probeAndApplyBaseUrl();
|
||||||
enabled: !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS,
|
|
||||||
).then((_) => AppConfig.probeAndApplyBaseUrl());
|
|
||||||
runApp(const LumaDramaApp());
|
runApp(const LumaDramaApp());
|
||||||
unawaited(
|
unawaited(
|
||||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
|
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
|
||||||
|
|||||||
@@ -119,10 +119,7 @@ class _AccountDeactivatePageState extends State<AccountDeactivatePage> {
|
|||||||
controller: _reason,
|
controller: _reason,
|
||||||
maxLength: AccountDeactivateLogic.maxReasonLength,
|
maxLength: AccountDeactivateLogic.maxReasonLength,
|
||||||
maxLines: 4,
|
maxLines: 4,
|
||||||
textAlignVertical: TextAlignVertical.top,
|
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
alignLabelWithHint: true,
|
|
||||||
floatingLabelBehavior: FloatingLabelBehavior.auto,
|
|
||||||
labelText: l10n.accountDeactivateReason,
|
labelText: l10n.accountDeactivateReason,
|
||||||
hintText: l10n.accountDeactivateReasonHint,
|
hintText: l10n.accountDeactivateReasonHint,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import 'package:provider/provider.dart';
|
|||||||
|
|
||||||
import '../../core/data/remote/api_client.dart';
|
import '../../core/data/remote/api_client.dart';
|
||||||
import '../../core/data/services/auth_controller.dart';
|
import '../../core/data/services/auth_controller.dart';
|
||||||
|
import '../../core/formatting/error_text.dart';
|
||||||
import '../../core/platform/haptics.dart';
|
import '../../core/platform/haptics.dart';
|
||||||
import '../../core/platform/keyboard_inset.dart';
|
import '../../core/platform/keyboard_inset.dart';
|
||||||
import '../../core/theme/app_colors.dart';
|
import '../../core/theme/app_colors.dart';
|
||||||
@@ -180,7 +181,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
|||||||
).showSnackBar(SnackBar(content: Text(l10n.authCodeSent)));
|
).showSnackBar(SnackBar(content: Text(l10n.authCodeSent)));
|
||||||
_codeFocus.requestFocus();
|
_codeFocus.requestFocus();
|
||||||
} on ApiException catch (error) {
|
} on ApiException catch (error) {
|
||||||
failureMessage = error.message;
|
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
failureMessage = l10n.authNetworkError;
|
failureMessage = l10n.authNetworkError;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -228,7 +229,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
|
|||||||
}
|
}
|
||||||
if (mounted) Navigator.of(context).pop(true);
|
if (mounted) Navigator.of(context).pop(true);
|
||||||
} on ApiException catch (error) {
|
} on ApiException catch (error) {
|
||||||
failureMessage = error.message;
|
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
failureMessage = l10n.authNetworkError;
|
failureMessage = l10n.authNetworkError;
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -23,18 +23,30 @@ import '../../core/widgets/catalog_debug_info.dart';
|
|||||||
import '../../core/widgets/catalog_endpoint_editor.dart';
|
import '../../core/widgets/catalog_endpoint_editor.dart';
|
||||||
import '../../core/widgets/empty_state.dart';
|
import '../../core/widgets/empty_state.dart';
|
||||||
import '../../l10n/app_localizations.dart';
|
import '../../l10n/app_localizations.dart';
|
||||||
|
import '../filter/filter_page.dart';
|
||||||
|
import '../new_releases/new_releases_page.dart';
|
||||||
import '../player/open_player.dart';
|
import '../player/open_player.dart';
|
||||||
|
import '../ranking/ranking_page.dart';
|
||||||
|
import '../reserve/reserve_page.dart';
|
||||||
import 'discover_binding.dart';
|
import 'discover_binding.dart';
|
||||||
import 'discover_logic.dart';
|
import 'discover_logic.dart';
|
||||||
import 'discover_types.dart';
|
import 'discover_types.dart';
|
||||||
import 'widgets/discover_category_tab.dart';
|
|
||||||
import 'widgets/discover_header.dart';
|
import 'widgets/discover_header.dart';
|
||||||
import 'widgets/discover_search_results.dart';
|
import 'widgets/discover_search_results.dart';
|
||||||
import 'widgets/discover_toolbar.dart';
|
|
||||||
import 'widgets/drama_grid.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 _categoryTabHeight = 44;
|
||||||
const double _categoryTabGap = 20;
|
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 double _stickyHeaderHeight = 44;
|
||||||
const Duration _stickyHeaderTransition = Duration(milliseconds: 160);
|
const Duration _stickyHeaderTransition = Duration(milliseconds: 160);
|
||||||
const Duration _categoryScrollDuration = Duration(milliseconds: 200);
|
const Duration _categoryScrollDuration = Duration(milliseconds: 200);
|
||||||
@@ -283,7 +295,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
|||||||
List<Widget> _theaterBlocks(AppLocalizations l10n) {
|
List<Widget> _theaterBlocks(AppLocalizations l10n) {
|
||||||
final dramas = theater.dramas;
|
final dramas = theater.dramas;
|
||||||
return [
|
return [
|
||||||
_toolbar(),
|
_toolbar(l10n),
|
||||||
if (dramas.isEmpty)
|
if (dramas.isEmpty)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 40),
|
padding: const EdgeInsets.symmetric(vertical: 40),
|
||||||
@@ -306,16 +318,6 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
|||||||
child: CircularProgressIndicator(strokeWidth: 2),
|
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),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -333,7 +335,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
|||||||
child: Row(
|
child: Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
DiscoverCategoryTab(
|
_categoryTab(
|
||||||
|
key: const Key('theater-category-all'),
|
||||||
anchorKey: _anchorFor('all'),
|
anchorKey: _anchorFor('all'),
|
||||||
id: 'all',
|
id: 'all',
|
||||||
label: l10n.all,
|
label: l10n.all,
|
||||||
@@ -342,7 +345,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
|||||||
),
|
),
|
||||||
for (final category in categories.categories) ...[
|
for (final category in categories.categories) ...[
|
||||||
const SizedBox(width: _categoryTabGap),
|
const SizedBox(width: _categoryTabGap),
|
||||||
DiscoverCategoryTab(
|
_categoryTab(
|
||||||
|
key: Key('theater-category-${category.id}'),
|
||||||
anchorKey: _anchorFor(category.id),
|
anchorKey: _anchorFor(category.id),
|
||||||
id: category.id,
|
id: category.id,
|
||||||
label: category.name,
|
label: category.name,
|
||||||
@@ -356,6 +360,52 @@ 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) {
|
GlobalKey _anchorFor(String id) {
|
||||||
return _categoryAnchors.putIfAbsent(id, GlobalKey.new);
|
return _categoryAnchors.putIfAbsent(id, GlobalKey.new);
|
||||||
}
|
}
|
||||||
@@ -394,8 +444,97 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _toolbar() {
|
Widget _toolbar(AppLocalizations l10n) {
|
||||||
return DiscoverToolbar(onOpen: (page) => _openPage(context, page));
|
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,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _openPage(BuildContext context, Widget page) {
|
void _openPage(BuildContext context, Widget page) {
|
||||||
@@ -462,3 +601,27 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
|||||||
AppRootTab.mine => DiscoverPageAction.mine,
|
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;
|
||||||
|
}
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
// 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;
|
|
||||||
}
|
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
// 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: [
|
children: [
|
||||||
_cover(),
|
_cover(),
|
||||||
const SizedBox(height: _titleGap),
|
const SizedBox(height: _titleGap),
|
||||||
_title(context),
|
_title(),
|
||||||
const SizedBox(height: _tagsGap),
|
const SizedBox(height: _tagsGap),
|
||||||
_tags(context),
|
_tags(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -151,9 +151,9 @@ class DramaGridCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _title(BuildContext context) {
|
Widget _title() {
|
||||||
return Text(
|
return Text(
|
||||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
drama.title,
|
||||||
key: Key('home-drama-title-${drama.id}'),
|
key: Key('home-drama-title-${drama.id}'),
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -166,8 +166,8 @@ class DramaGridCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _tags(BuildContext context) {
|
Widget _tags() {
|
||||||
final tags = _tagValues(context);
|
final tags = _tagValues();
|
||||||
if (tags.isEmpty) return const SizedBox.shrink();
|
if (tags.isEmpty) return const SizedBox.shrink();
|
||||||
return Wrap(
|
return Wrap(
|
||||||
spacing: 6,
|
spacing: 6,
|
||||||
@@ -193,9 +193,7 @@ class DramaGridCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _tagValues(BuildContext context) {
|
List<String> _tagValues() {
|
||||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
|
||||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
|
||||||
final result = <String>[];
|
final result = <String>[];
|
||||||
for (final value in [drama.genre, drama.category]) {
|
for (final value in [drama.genre, drama.category]) {
|
||||||
for (final part in value.split(_tagSplitter)) {
|
for (final part in value.split(_tagSplitter)) {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ class SearchResultCard extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final tags = _tags(context);
|
final tags = _tags();
|
||||||
return Material(
|
return Material(
|
||||||
key: Key('search-result-card-${drama.id}'),
|
key: Key('search-result-card-${drama.id}'),
|
||||||
color: AppColors.transparent,
|
color: AppColors.transparent,
|
||||||
@@ -60,7 +60,7 @@ class SearchResultCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: AppDimens.searchResultTitleGap),
|
const SizedBox(height: AppDimens.searchResultTitleGap),
|
||||||
Text(
|
Text(
|
||||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
drama.title,
|
||||||
key: Key('search-result-title-${drama.id}'),
|
key: Key('search-result-title-${drama.id}'),
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -92,9 +92,7 @@ class SearchResultCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _tags(BuildContext context) {
|
List<String> _tags() {
|
||||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
|
||||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
|
||||||
final seen = <String>{};
|
final seen = <String>{};
|
||||||
return [drama.genre, drama.category]
|
return [drama.genre, drama.category]
|
||||||
.expand((value) => value.split(RegExp(r'[,/、·]')))
|
.expand((value) => value.split(RegExp(r'[,/、·]')))
|
||||||
|
|||||||
@@ -163,10 +163,8 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
|||||||
synopsis: localizedDramaSynopsis(l10n, drama),
|
synopsis: localizedDramaSynopsis(l10n, drama),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (_tagValues(context, drama).isNotEmpty)
|
if (_tagValues(drama).isNotEmpty)
|
||||||
SliverToBoxAdapter(
|
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(drama))),
|
||||||
child: DramaTags(tags: _tagValues(context, drama)),
|
|
||||||
),
|
|
||||||
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
|
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
|
||||||
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
||||||
],
|
],
|
||||||
@@ -398,14 +396,11 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _toggleFavorite(AppLocalizations l10n) async {
|
Future<void> _toggleFavorite(AppLocalizations l10n) async {
|
||||||
|
if (!await ensureSignedIn(context)) return;
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
unawaited(context.read<Haptics>().lightImpact());
|
unawaited(context.read<Haptics>().lightImpact());
|
||||||
final ok = await logic.toggleFavorite();
|
final ok = await logic.toggleFavorite();
|
||||||
if (ok || !mounted) return;
|
if (ok || !mounted) return;
|
||||||
if (logic.favorites.lastErrorCode == 200007) {
|
|
||||||
await ensureSignedIn(context);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ScaffoldMessenger.of(
|
ScaffoldMessenger.of(
|
||||||
context,
|
context,
|
||||||
).showSnackBar(SnackBar(content: Text(l10n.favoriteToggleFailed)));
|
).showSnackBar(SnackBar(content: Text(l10n.favoriteToggleFailed)));
|
||||||
@@ -447,20 +442,13 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
|||||||
return record.fraction;
|
return record.fraction;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _tagValues(BuildContext context, Drama drama) {
|
List<String> _tagValues(Drama drama) {
|
||||||
final localized = drama.localizedTypeLabels(
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
);
|
|
||||||
final result = <String>[];
|
final result = <String>[];
|
||||||
if (localized.isNotEmpty) {
|
for (final source in [drama.category, drama.genre]) {
|
||||||
result.addAll(localized.take(_maxTags));
|
for (final part in source.split(_tagSplitter)) {
|
||||||
} else {
|
final value = part.trim();
|
||||||
for (final source in [drama.category, drama.genre]) {
|
if (value.isNotEmpty && !result.contains(value)) result.add(value);
|
||||||
for (final part in source.split(_tagSplitter)) {
|
if (result.length == _maxTags) return result;
|
||||||
final value = part.trim();
|
|
||||||
if (value.isNotEmpty && !result.contains(value)) result.add(value);
|
|
||||||
if (result.length == _maxTags) return result;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
final language = drama.language.trim();
|
final language = drama.language.trim();
|
||||||
|
|||||||
@@ -176,8 +176,6 @@ class _FavoritesBody extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
PagedListFooter(
|
PagedListFooter(
|
||||||
loading: favorites.loadingMore,
|
loading: favorites.loadingMore,
|
||||||
hasMore: favorites.hasMore,
|
|
||||||
hasItems: favorites.cards.isNotEmpty,
|
|
||||||
errorMessage: favorites.loadMoreError == null
|
errorMessage: favorites.loadMoreError == null
|
||||||
? null
|
? null
|
||||||
: errorText(l10n, favorites.loadMoreError, l10n.favoritesError),
|
: errorText(l10n, favorites.loadMoreError, l10n.favoritesError),
|
||||||
@@ -267,9 +265,8 @@ class _FavoriteCard extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final languageCode = Localizations.localeOf(context).languageCode;
|
final tags = _tags();
|
||||||
final tags = _tags(languageCode);
|
final synopsis = drama.synopsis.trim();
|
||||||
final synopsis = drama.localizedSynopsis(languageCode).trim();
|
|
||||||
return Container(
|
return Container(
|
||||||
key: ValueKey('favorite-card-${drama.id}'),
|
key: ValueKey('favorite-card-${drama.id}'),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@@ -312,7 +309,7 @@ class _FavoriteCard extends StatelessWidget {
|
|||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
drama.localizedTitle(languageCode),
|
drama.title,
|
||||||
key: ValueKey('favorite-title-${drama.id}'),
|
key: ValueKey('favorite-title-${drama.id}'),
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -447,9 +444,7 @@ class _FavoriteCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _tags(String languageCode) {
|
List<String> _tags() {
|
||||||
final localized = drama.localizedTypeLabels(languageCode);
|
|
||||||
if (localized.isNotEmpty) return localized.take(_maxTags).toList();
|
|
||||||
final values = <String>[];
|
final values = <String>[];
|
||||||
for (final source in [drama.genre, drama.category]) {
|
for (final source in [drama.genre, drama.category]) {
|
||||||
for (final part in source.split(_tagSplitter)) {
|
for (final part in source.split(_tagSplitter)) {
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ class FollowingFavoritesGrid extends StatelessWidget {
|
|||||||
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
|
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
|
||||||
return FollowingGridCard(
|
return FollowingGridCard(
|
||||||
dramaId: drama.id,
|
dramaId: drama.id,
|
||||||
title: drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
title: drama.title,
|
||||||
posterUrl: drama.posterUrl,
|
posterUrl: drama.posterUrl,
|
||||||
viewCount: drama.viewCount,
|
viewCount: drama.viewCount,
|
||||||
editing: isEditing,
|
editing: isEditing,
|
||||||
|
|||||||
@@ -402,11 +402,7 @@ class _HistoryList extends StatelessWidget {
|
|||||||
|
|
||||||
return FollowingHistoryCard(
|
return FollowingHistoryCard(
|
||||||
dramaId: record.dramaId,
|
dramaId: record.dramaId,
|
||||||
title: _historyTitle(
|
title: _historyTitle(l10n, record),
|
||||||
l10n,
|
|
||||||
record,
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
),
|
|
||||||
posterUrl: record.displayCover,
|
posterUrl: record.displayCover,
|
||||||
viewCount:
|
viewCount:
|
||||||
record.progress.viewCount ??
|
record.progress.viewCount ??
|
||||||
@@ -437,13 +433,10 @@ class _HistoryList extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String _historyTitle(
|
String _historyTitle(AppLocalizations l10n, WatchRecord record) {
|
||||||
AppLocalizations l10n,
|
return record.displayTitle.isEmpty
|
||||||
WatchRecord record,
|
? l10n.episodeLabel(record.episodeNumber)
|
||||||
String languageCode,
|
: record.displayTitle;
|
||||||
) {
|
|
||||||
final title = record.localizedDisplayTitle(languageCode);
|
|
||||||
return title.isEmpty ? l10n.episodeLabel(record.episodeNumber) : title;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String _historySubtitle(AppLocalizations l10n, WatchRecord record) {
|
String _historySubtitle(AppLocalizations l10n, WatchRecord record) {
|
||||||
|
|||||||
@@ -130,8 +130,6 @@ class FollowingPagedGrid extends StatelessWidget {
|
|||||||
SliverToBoxAdapter(
|
SliverToBoxAdapter(
|
||||||
child: PagedListFooter(
|
child: PagedListFooter(
|
||||||
loading: loadingMore,
|
loading: loadingMore,
|
||||||
hasMore: hasMore,
|
|
||||||
hasItems: hasItems,
|
|
||||||
errorMessage: loadMoreError,
|
errorMessage: loadMoreError,
|
||||||
onRetry: onLoadMore,
|
onRetry: onLoadMore,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import 'package:flutter/services.dart';
|
|||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../../core/config/app_config.dart';
|
import '../../core/config/app_config.dart';
|
||||||
import '../../core/data/remote/catalog_api.dart';
|
|
||||||
import '../../core/data/services/home_feed_controller.dart';
|
import '../../core/data/services/home_feed_controller.dart';
|
||||||
import '../../core/data/services/catalog_controller.dart';
|
import '../../core/data/services/catalog_controller.dart';
|
||||||
import '../../core/data/services/category_controller.dart';
|
import '../../core/data/services/category_controller.dart';
|
||||||
@@ -210,7 +209,6 @@ class _HomeTabsState extends State<_HomeTabs> {
|
|||||||
Widget _recommend(BuildContext context) {
|
Widget _recommend(BuildContext context) {
|
||||||
return RecommendPage(
|
return RecommendPage(
|
||||||
feedController: widget.feedController,
|
feedController: widget.feedController,
|
||||||
catalogApi: _catalogApi(context),
|
|
||||||
active: logic.tab == 1,
|
active: logic.tab == 1,
|
||||||
videoOnly: logic.videoImmersive,
|
videoOnly: logic.videoImmersive,
|
||||||
onImmersiveChanged: logic.onImmersiveChanged,
|
onImmersiveChanged: logic.onImmersiveChanged,
|
||||||
@@ -218,14 +216,6 @@ class _HomeTabsState extends State<_HomeTabs> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
CatalogApi? _catalogApi(BuildContext context) {
|
|
||||||
try {
|
|
||||||
return context.read<CatalogApi>();
|
|
||||||
} on ProviderNotFoundException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _openSearch(BuildContext context) {
|
void _openSearch(BuildContext context) {
|
||||||
Navigator.of(
|
Navigator.of(
|
||||||
context,
|
context,
|
||||||
|
|||||||
@@ -1,178 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
|
||||||
|
|
||||||
import '../../../core/data/models/drama.dart';
|
|
||||||
import '../../../core/data/services/category_controller.dart';
|
|
||||||
import '../../../core/theme/app_dimens.dart';
|
|
||||||
import '../../../core/widgets/app_pull_to_refresh.dart';
|
|
||||||
import '../../../core/widgets/drama_grid_skeleton.dart';
|
|
||||||
import '../../../core/widgets/empty_state.dart';
|
|
||||||
import '../../../core/widgets/paged_list_footer.dart';
|
|
||||||
import '../../../l10n/app_localizations.dart';
|
|
||||||
import 'home_feed_card.dart';
|
|
||||||
|
|
||||||
const double _loadMoreThreshold = 240;
|
|
||||||
|
|
||||||
/// 首页分类下的短剧:按分类分页,滑到底加载下一页。
|
|
||||||
class HomeCategoryDramas extends StatefulWidget {
|
|
||||||
const HomeCategoryDramas({
|
|
||||||
super.key,
|
|
||||||
required this.onOpenDrama,
|
|
||||||
this.lockedCategoryId,
|
|
||||||
});
|
|
||||||
|
|
||||||
final ValueChanged<Drama> onOpenDrama;
|
|
||||||
final String? lockedCategoryId;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<HomeCategoryDramas> createState() => _HomeCategoryDramasState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _HomeCategoryDramasState extends State<HomeCategoryDramas> {
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _ensureOpened());
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(HomeCategoryDramas oldWidget) {
|
|
||||||
super.didUpdateWidget(oldWidget);
|
|
||||||
if (oldWidget.lockedCategoryId != widget.lockedCategoryId) {
|
|
||||||
_ensureOpened();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _ensureOpened() {
|
|
||||||
if (!mounted) return;
|
|
||||||
final controller = context.read<CategoryController>();
|
|
||||||
final locked = widget.lockedCategoryId;
|
|
||||||
if (locked == null || locked.isEmpty) return;
|
|
||||||
final slot = controller.slotOf(locked);
|
|
||||||
if (slot.loading || slot.pageIndex > 0) return;
|
|
||||||
unawaited(controller.openCategory(locked));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _onScroll(ScrollNotification notification) {
|
|
||||||
final categoryId = widget.lockedCategoryId;
|
|
||||||
if (categoryId == null || categoryId.isEmpty) return false;
|
|
||||||
if (notification.depth != 0) return false;
|
|
||||||
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
|
|
||||||
if (notification is! ScrollUpdateNotification &&
|
|
||||||
notification is! ScrollEndNotification &&
|
|
||||||
notification is! OverscrollNotification) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
unawaited(context.read<CategoryController>().loadMore(categoryId));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final l10n = AppLocalizations.of(context)!;
|
|
||||||
final controller = context.watch<CategoryController>();
|
|
||||||
final categoryId = widget.lockedCategoryId ?? '';
|
|
||||||
final slot = categoryId.isEmpty ? null : controller.slotOf(categoryId);
|
|
||||||
final dramas = slot?.dramas ?? const <Drama>[];
|
|
||||||
return Column(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: NotificationListener<ScrollNotification>(
|
|
||||||
onNotification: _onScroll,
|
|
||||||
child: AppPullToRefresh(
|
|
||||||
onRefresh: () async {
|
|
||||||
if (categoryId.isNotEmpty) {
|
|
||||||
await controller.openCategory(categoryId);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
child: _body(context, l10n, controller, categoryId, dramas),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _body(
|
|
||||||
BuildContext context,
|
|
||||||
AppLocalizations l10n,
|
|
||||||
CategoryController controller,
|
|
||||||
String categoryId,
|
|
||||||
List<Drama> dramas,
|
|
||||||
) {
|
|
||||||
final slot = categoryId.isEmpty ? null : controller.slotOf(categoryId);
|
|
||||||
if (slot != null && slot.loading && dramas.isEmpty) {
|
|
||||||
return const DramaGridSkeleton(
|
|
||||||
key: Key('home-grid-skeleton'),
|
|
||||||
columns: 3,
|
|
||||||
horizontalPadding: AppDimens.feedPageHorizontal,
|
|
||||||
crossAxisSpacing: AppDimens.homeGridGap,
|
|
||||||
mainAxisSpacing: AppDimens.homeGridRowGap,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (dramas.isEmpty) {
|
|
||||||
return EmptyState(
|
|
||||||
key: const Key('home-grid-empty'),
|
|
||||||
icon: Icons.movie_filter_outlined,
|
|
||||||
title: l10n.emptyContent,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final itemWidth =
|
|
||||||
(constraints.maxWidth -
|
|
||||||
AppDimens.feedPageHorizontal * 2 -
|
|
||||||
AppDimens.homeGridGap * 2) /
|
|
||||||
3;
|
|
||||||
final itemExtent =
|
|
||||||
itemWidth / AppDimens.cardCoverAspectRatio +
|
|
||||||
AppDimens.homeCardBodyExtent;
|
|
||||||
return CustomScrollView(
|
|
||||||
key: const Key('home-grid-scroll'),
|
|
||||||
physics: AppPullToRefresh.physics,
|
|
||||||
slivers: [
|
|
||||||
SliverPadding(
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: AppDimens.feedPageHorizontal,
|
|
||||||
),
|
|
||||||
sliver: SliverGrid(
|
|
||||||
key: const Key('home-grid-cards'),
|
|
||||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
|
||||||
crossAxisCount: 3,
|
|
||||||
crossAxisSpacing: AppDimens.homeGridGap,
|
|
||||||
mainAxisSpacing: AppDimens.homeGridRowGap,
|
|
||||||
mainAxisExtent: itemExtent,
|
|
||||||
),
|
|
||||||
delegate: SliverChildBuilderDelegate(
|
|
||||||
(context, index) => HomeFeedCard(
|
|
||||||
drama: dramas[index],
|
|
||||||
onTap: () => widget.onOpenDrama(dramas[index]),
|
|
||||||
),
|
|
||||||
childCount: dramas.length,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
SliverToBoxAdapter(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
|
|
||||||
child: PagedListFooter(
|
|
||||||
loading: slot != null && slot.loadingMore,
|
|
||||||
hasMore: slot?.hasMore ?? false,
|
|
||||||
hasItems: dramas.isNotEmpty,
|
|
||||||
errorMessage: null,
|
|
||||||
onRetry: () => context.read<CategoryController>().loadMore(
|
|
||||||
categoryId,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -99,9 +99,9 @@ class HomeDramaCard extends StatelessWidget {
|
|||||||
children: [
|
children: [
|
||||||
_cover(),
|
_cover(),
|
||||||
const SizedBox(height: _coverTitleGap),
|
const SizedBox(height: _coverTitleGap),
|
||||||
_title(context),
|
_title(),
|
||||||
const SizedBox(height: _lineGap),
|
const SizedBox(height: _lineGap),
|
||||||
_genre(context),
|
_genre(),
|
||||||
const SizedBox(height: _lineGap),
|
const SizedBox(height: _lineGap),
|
||||||
_metadata(),
|
_metadata(),
|
||||||
],
|
],
|
||||||
@@ -211,9 +211,9 @@ class HomeDramaCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _title(BuildContext context) {
|
Widget _title() {
|
||||||
return Text(
|
return Text(
|
||||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
drama.title,
|
||||||
key: Key('home-drama-title-${drama.id}'),
|
key: Key('home-drama-title-${drama.id}'),
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -225,11 +225,8 @@ class HomeDramaCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _genre(BuildContext context) {
|
Widget _genre() {
|
||||||
final labels = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
final genre = drama.genre.isEmpty ? drama.category : drama.genre;
|
||||||
final genre = labels.isEmpty
|
|
||||||
? (drama.genre.isEmpty ? drama.category : drama.genre)
|
|
||||||
: labels.join(' / ');
|
|
||||||
return Text(
|
return Text(
|
||||||
genre.isEmpty ? l10n.videoPending : genre,
|
genre.isEmpty ? l10n.videoPending : genre,
|
||||||
key: Key('home-drama-genre-${drama.id}'),
|
key: Key('home-drama-genre-${drama.id}'),
|
||||||
|
|||||||
@@ -8,21 +8,28 @@ import '../../../core/theme/app_dimens.dart';
|
|||||||
import '../../../core/widgets/cover_play_count.dart';
|
import '../../../core/widgets/cover_play_count.dart';
|
||||||
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
|
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
|
||||||
import '../../../core/widgets/remote_image.dart';
|
import '../../../core/widgets/remote_image.dart';
|
||||||
|
import '../../../l10n/app_localizations.dart';
|
||||||
|
import 'home_drama_classification.dart';
|
||||||
|
|
||||||
final RegExp _tagSplitter = RegExp(r'[,/、·]');
|
final RegExp _tagSplitter = RegExp(r'[,/、·]');
|
||||||
|
|
||||||
|
enum HomeDramaBadge { hot, newRelease, anime }
|
||||||
|
|
||||||
class HomeFeedCard extends StatelessWidget {
|
class HomeFeedCard extends StatelessWidget {
|
||||||
const HomeFeedCard({
|
const HomeFeedCard({
|
||||||
super.key,
|
super.key,
|
||||||
required this.drama,
|
required this.drama,
|
||||||
required this.onTap,
|
required this.onTap,
|
||||||
|
this.now,
|
||||||
});
|
});
|
||||||
|
|
||||||
final Drama drama;
|
final Drama drama;
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
|
final DateTime? now;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final l10n = AppLocalizations.of(context)!;
|
||||||
return Material(
|
return Material(
|
||||||
key: Key('home-feed-card-${drama.id}'),
|
key: Key('home-feed-card-${drama.id}'),
|
||||||
color: AppColors.transparent,
|
color: AppColors.transparent,
|
||||||
@@ -33,7 +40,7 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
mainAxisAlignment: MainAxisAlignment.start,
|
mainAxisAlignment: MainAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
_cover(context),
|
_cover(l10n),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.only(
|
padding: const EdgeInsets.only(
|
||||||
@@ -44,7 +51,7 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
mainAxisAlignment: MainAxisAlignment.start,
|
mainAxisAlignment: MainAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
drama.title,
|
||||||
key: Key('home-feed-title-${drama.id}'),
|
key: Key('home-feed-title-${drama.id}'),
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -57,7 +64,7 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppDimens.cardTitleTagGap),
|
const SizedBox(height: AppDimens.cardTitleTagGap),
|
||||||
_tags(context),
|
_tags(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -68,8 +75,8 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _cover(BuildContext context) {
|
Widget _cover(AppLocalizations l10n) {
|
||||||
final label = drama.localizedTag(Localizations.localeOf(context).languageCode);
|
final badge = _badge();
|
||||||
return ClipRRect(
|
return ClipRRect(
|
||||||
key: Key('home-feed-cover-clip-${drama.id}'),
|
key: Key('home-feed-cover-clip-${drama.id}'),
|
||||||
borderRadius: BorderRadius.circular(AppDimens.cardCoverRadius),
|
borderRadius: BorderRadius.circular(AppDimens.cardCoverRadius),
|
||||||
@@ -85,14 +92,14 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
showFallbackIcon: true,
|
showFallbackIcon: true,
|
||||||
fallbackColor: AppColors.contentSurface,
|
fallbackColor: AppColors.contentSurface,
|
||||||
),
|
),
|
||||||
if (label.isNotEmpty)
|
if (badge != null)
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 0,
|
top: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: DramaCoverBadgeRibbon(
|
child: DramaCoverBadgeRibbon(
|
||||||
label: label,
|
label: _badgeLabel(l10n, badge),
|
||||||
color: drama.tagRibbonColor(AppColors.badgeHot),
|
color: _badgeColor(badge),
|
||||||
keyPrefix: '${drama.id}-tag',
|
keyPrefix: '${drama.id}-${badge.name}',
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Positioned(
|
const Positioned(
|
||||||
@@ -115,8 +122,35 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _tags(BuildContext context) {
|
HomeDramaBadge? _badge() {
|
||||||
final tags = _cardTags(context);
|
if (drama.dramaType.toUpperCase() == 'ANIME') {
|
||||||
|
return HomeDramaBadge.anime;
|
||||||
|
}
|
||||||
|
if (isNewDrama(drama, now: now)) return HomeDramaBadge.newRelease;
|
||||||
|
if (isHotDrama(drama)) {
|
||||||
|
return HomeDramaBadge.hot;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String _badgeLabel(AppLocalizations l10n, HomeDramaBadge badge) {
|
||||||
|
return switch (badge) {
|
||||||
|
HomeDramaBadge.hot => l10n.homeBadgeHot,
|
||||||
|
HomeDramaBadge.newRelease => l10n.homeBadgeNew,
|
||||||
|
HomeDramaBadge.anime => l10n.homeBadgeAnime,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Color _badgeColor(HomeDramaBadge badge) {
|
||||||
|
return switch (badge) {
|
||||||
|
HomeDramaBadge.hot => AppColors.badgeHot,
|
||||||
|
HomeDramaBadge.newRelease => AppColors.badgeNew,
|
||||||
|
HomeDramaBadge.anime => AppColors.badgeAnime,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _tags() {
|
||||||
|
final tags = _cardTags();
|
||||||
if (tags.isEmpty) return const SizedBox.shrink();
|
if (tags.isEmpty) return const SizedBox.shrink();
|
||||||
return Text(
|
return Text(
|
||||||
tags.join(' | '),
|
tags.join(' | '),
|
||||||
@@ -132,9 +166,7 @@ class HomeFeedCard extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _cardTags(BuildContext context) {
|
List<String> _cardTags() {
|
||||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
|
||||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
|
||||||
final seen = <String>{};
|
final seen = <String>{};
|
||||||
return [drama.genre, drama.category]
|
return [drama.genre, drama.category]
|
||||||
.expand((value) => value.split(_tagSplitter))
|
.expand((value) => value.split(_tagSplitter))
|
||||||
|
|||||||
@@ -14,16 +14,20 @@ import '../../../core/data/services/home_feed_controller.dart';
|
|||||||
import '../../../core/data/services/wallet_controller.dart';
|
import '../../../core/data/services/wallet_controller.dart';
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
import '../../../core/theme/app_dimens.dart';
|
import '../../../core/theme/app_dimens.dart';
|
||||||
|
import '../../../core/theme/app_theme.dart';
|
||||||
import '../../../core/widgets/app_pull_to_refresh.dart';
|
import '../../../core/widgets/app_pull_to_refresh.dart';
|
||||||
import '../../../core/widgets/drama_grid_skeleton.dart';
|
import '../../../core/widgets/drama_grid_skeleton.dart';
|
||||||
import '../../../core/widgets/empty_state.dart';
|
import '../../../core/widgets/empty_state.dart';
|
||||||
import '../../../core/widgets/paged_list_footer.dart';
|
import '../../../core/widgets/paged_list_footer.dart';
|
||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
import 'home_category_dramas.dart';
|
import '../../ranking/ranking_page.dart';
|
||||||
|
import 'home_drama_classification.dart';
|
||||||
import 'home_feed_card.dart';
|
import 'home_feed_card.dart';
|
||||||
import 'home_grid_header.dart';
|
import 'home_grid_header.dart';
|
||||||
|
|
||||||
const double _loadMoreThreshold = 240;
|
const double _loadMoreThreshold = 240;
|
||||||
|
const List<String> _costumeAliases = ['古装', 'costume', 'period'];
|
||||||
|
const List<String> _communityAliases = ['社群', 'community', 'komunitas'];
|
||||||
|
|
||||||
class HomeFeedGrid extends StatefulWidget {
|
class HomeFeedGrid extends StatefulWidget {
|
||||||
const HomeFeedGrid({
|
const HomeFeedGrid({
|
||||||
@@ -42,15 +46,21 @@ class HomeFeedGrid extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _HomeFeedGridState extends State<HomeFeedGrid> {
|
class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||||
int _sectionIndex = 0;
|
HomePrimaryTab _selectedPrimary = HomePrimaryTab.featured;
|
||||||
final PageController _pageController = PageController();
|
final PageController _pageController = PageController();
|
||||||
|
final Map<HomePrimaryTab, ScrollController> _scrollControllers = {
|
||||||
|
for (final tab in HomePrimaryTab.values) tab: ScrollController(),
|
||||||
|
};
|
||||||
|
final Map<HomePrimaryTab, String?> _selectedTags = {
|
||||||
|
for (final tab in HomePrimaryTab.values) tab: null,
|
||||||
|
};
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
if (mounted && _pageController.hasClients) {
|
if (mounted && _pageController.hasClients) {
|
||||||
_pageController.jumpToPage(_sectionIndex);
|
_pageController.jumpToPage(_selectedPrimary.index);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -58,6 +68,9 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_pageController.dispose();
|
_pageController.dispose();
|
||||||
|
for (final controller in _scrollControllers.values) {
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,16 +81,17 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
final catalog = context.watch<CatalogController>();
|
final catalog = context.watch<CatalogController>();
|
||||||
final auth = context.watch<AuthController>();
|
final auth = context.watch<AuthController>();
|
||||||
final wallet = context.watch<WalletController>();
|
final wallet = context.watch<WalletController>();
|
||||||
final shortcuts = _categoryShortcuts(
|
final shortcuts = _categoryShortcuts(categories, l10n);
|
||||||
categories,
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
);
|
|
||||||
final walletBadge = auth.isSignedIn && wallet.snapshot != null
|
final walletBadge = auth.isSignedIn && wallet.snapshot != null
|
||||||
? wallet.balance
|
? wallet.balance
|
||||||
: null;
|
: null;
|
||||||
|
final ranking = _selectedPrimary == HomePrimaryTab.ranking;
|
||||||
return DecoratedBox(
|
return DecoratedBox(
|
||||||
key: const Key('home-grid'),
|
key: const Key('home-grid'),
|
||||||
decoration: const BoxDecoration(color: AppColors.appBackground),
|
decoration: BoxDecoration(
|
||||||
|
color: ranking ? null : AppColors.appBackground,
|
||||||
|
gradient: ranking ? AppTheme.pageGradient : null,
|
||||||
|
),
|
||||||
child: SafeArea(
|
child: SafeArea(
|
||||||
bottom: false,
|
bottom: false,
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -86,8 +100,8 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
HomeGridHeader(
|
HomeGridHeader(
|
||||||
callbacks: widget.callbacks,
|
callbacks: widget.callbacks,
|
||||||
categories: shortcuts,
|
categories: shortcuts,
|
||||||
selectedIndex: _sectionIndex,
|
selectedPrimary: _selectedPrimary,
|
||||||
onSectionSelected: _selectSection,
|
onPrimarySelected: _selectPrimary,
|
||||||
walletBadge: walletBadge,
|
walletBadge: walletBadge,
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -96,30 +110,22 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
builder: (context, _) => PageView.builder(
|
builder: (context, _) => PageView.builder(
|
||||||
key: const Key('home-primary-page-view'),
|
key: const Key('home-primary-page-view'),
|
||||||
controller: _pageController,
|
controller: _pageController,
|
||||||
itemCount: shortcuts.isEmpty ? 1 : shortcuts.length,
|
itemCount: HomePrimaryTab.values.length,
|
||||||
onPageChanged: (index) =>
|
onPageChanged: (index) => setState(
|
||||||
setState(() => _sectionIndex = index),
|
() => _selectedPrimary = HomePrimaryTab.values[index],
|
||||||
itemBuilder: (context, index) {
|
),
|
||||||
if (shortcuts.isEmpty) {
|
itemBuilder: (context, index) => _KeepAlivePage(
|
||||||
return _categoryPlaceholder(
|
key: PageStorageKey(
|
||||||
l10n,
|
'home-primary-page-${HomePrimaryTab.values[index].name}',
|
||||||
context.watch<CategoryController>(),
|
),
|
||||||
catalog,
|
child: _tabGrid(
|
||||||
);
|
context,
|
||||||
}
|
l10n,
|
||||||
final category = shortcuts[index];
|
tab: HomePrimaryTab.values[index],
|
||||||
return _KeepAlivePage(
|
catalog: catalog,
|
||||||
key: PageStorageKey(
|
shortcuts: shortcuts,
|
||||||
'home-primary-page-${category.categoryId}',
|
),
|
||||||
),
|
),
|
||||||
child: _tabGrid(
|
|
||||||
context,
|
|
||||||
l10n,
|
|
||||||
category: category,
|
|
||||||
catalog: catalog,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -129,58 +135,28 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _selectSection(int index) {
|
void _selectPrimary(HomePrimaryTab tab) {
|
||||||
if (index == _sectionIndex) return;
|
if (tab == _selectedPrimary) return;
|
||||||
if (!_pageController.hasClients) {
|
if (!_pageController.hasClients) {
|
||||||
setState(() => _sectionIndex = index);
|
setState(() => _selectedPrimary = tab);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
unawaited(
|
unawaited(
|
||||||
_pageController.animateToPage(
|
_pageController.animateToPage(
|
||||||
index,
|
tab.index,
|
||||||
duration: AppDimens.homePrimaryTabAnimationDuration,
|
duration: AppDimens.homePrimaryTabAnimationDuration,
|
||||||
curve: Curves.easeOut,
|
curve: Curves.easeOut,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _categoryPlaceholder(
|
|
||||||
AppLocalizations l10n,
|
|
||||||
CategoryController controller,
|
|
||||||
CatalogController catalog,
|
|
||||||
) {
|
|
||||||
if (catalog.error != null) {
|
|
||||||
return _catalogErrorState(l10n, catalog);
|
|
||||||
}
|
|
||||||
if (controller.loading) {
|
|
||||||
return const DramaGridSkeleton(
|
|
||||||
key: Key('home-grid-skeleton'),
|
|
||||||
columns: 3,
|
|
||||||
horizontalPadding: AppDimens.feedPageHorizontal,
|
|
||||||
crossAxisSpacing: AppDimens.homeGridGap,
|
|
||||||
mainAxisSpacing: AppDimens.homeGridRowGap,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return EmptyState(
|
|
||||||
key: const Key('home-grid-empty'),
|
|
||||||
icon: Icons.movie_filter_outlined,
|
|
||||||
title: l10n.emptyContent,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _tabGrid(
|
Widget _tabGrid(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
AppLocalizations l10n, {
|
AppLocalizations l10n, {
|
||||||
required HomeGridCategoryShortcut category,
|
required HomePrimaryTab tab,
|
||||||
required CatalogController catalog,
|
required CatalogController catalog,
|
||||||
|
required List<HomeGridCategoryShortcut> shortcuts,
|
||||||
}) {
|
}) {
|
||||||
final controller = context.read<CategoryController>();
|
|
||||||
if (controller.dramaPageLoader != null && category.categoryId.isNotEmpty) {
|
|
||||||
return HomeCategoryDramas(
|
|
||||||
lockedCategoryId: category.categoryId,
|
|
||||||
onOpenDrama: widget.onOpenDrama,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (catalog.error != null && widget.feedController.dramas.isEmpty) {
|
if (catalog.error != null && widget.feedController.dramas.isEmpty) {
|
||||||
return _catalogErrorState(l10n, catalog);
|
return _catalogErrorState(l10n, catalog);
|
||||||
}
|
}
|
||||||
@@ -194,7 +170,11 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
mainAxisSpacing: AppDimens.homeGridRowGap,
|
mainAxisSpacing: AppDimens.homeGridRowGap,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final dramas = _dramasFor(category);
|
if (tab == HomePrimaryTab.ranking) {
|
||||||
|
return const RankingPage(embedded: true);
|
||||||
|
}
|
||||||
|
final tag = _selectedTags[tab];
|
||||||
|
final dramas = _dramasFor(tab, tag, shortcuts);
|
||||||
if (widget.feedController.loadingFirstPage && dramas.isEmpty) {
|
if (widget.feedController.loadingFirstPage && dramas.isEmpty) {
|
||||||
return const DramaGridSkeleton(
|
return const DramaGridSkeleton(
|
||||||
key: Key('home-grid-skeleton'),
|
key: Key('home-grid-skeleton'),
|
||||||
@@ -221,7 +201,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
onRefresh: _refresh,
|
onRefresh: _refresh,
|
||||||
child: CustomScrollView(
|
child: CustomScrollView(
|
||||||
key: const Key('home-grid-scroll'),
|
key: const Key('home-grid-scroll'),
|
||||||
controller: null,
|
controller: _scrollControllers[tab],
|
||||||
physics: AppPullToRefresh.physics,
|
physics: AppPullToRefresh.physics,
|
||||||
slivers: [
|
slivers: [
|
||||||
if (dramas.isEmpty)
|
if (dramas.isEmpty)
|
||||||
@@ -257,8 +237,6 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
|
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
|
||||||
child: PagedListFooter(
|
child: PagedListFooter(
|
||||||
loading: widget.feedController.loadingMore,
|
loading: widget.feedController.loadingMore,
|
||||||
hasMore: widget.feedController.hasMore,
|
|
||||||
hasItems: true,
|
|
||||||
errorMessage: widget.feedController.lastError == null
|
errorMessage: widget.feedController.lastError == null
|
||||||
? null
|
? null
|
||||||
: l10n.catalogError,
|
: l10n.catalogError,
|
||||||
@@ -311,31 +289,75 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
|||||||
|
|
||||||
List<HomeGridCategoryShortcut> _categoryShortcuts(
|
List<HomeGridCategoryShortcut> _categoryShortcuts(
|
||||||
List<ContentCategory> categories,
|
List<ContentCategory> categories,
|
||||||
String languageCode,
|
AppLocalizations l10n,
|
||||||
) {
|
) {
|
||||||
|
final costume = _findCategory(categories, _costumeAliases);
|
||||||
|
final community = _findCategory(categories, _communityAliases);
|
||||||
return [
|
return [
|
||||||
for (final category in categories)
|
HomeGridCategoryShortcut(
|
||||||
HomeGridCategoryShortcut(
|
label: l10n.homeSectionCostume,
|
||||||
label: category.localizedName(languageCode),
|
categoryName: costume?.name ?? '',
|
||||||
categoryName: category.name,
|
tab: HomePrimaryTab.costume,
|
||||||
categoryId: category.id,
|
),
|
||||||
tab: HomePrimaryTab.categories,
|
HomeGridCategoryShortcut(
|
||||||
),
|
label: l10n.homeSectionCommunity,
|
||||||
|
categoryName: community?.name ?? '',
|
||||||
|
tab: HomePrimaryTab.community,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Drama> _dramasFor(HomeGridCategoryShortcut category) {
|
ContentCategory? _findCategory(
|
||||||
final dramas = widget.feedController.dramas;
|
List<ContentCategory> categories,
|
||||||
final categoryName = category.categoryName.toLowerCase();
|
List<String> aliases,
|
||||||
if (categoryName.isEmpty) return dramas;
|
) {
|
||||||
final matched = dramas
|
for (final category in categories) {
|
||||||
.where(
|
final name = category.name.toLowerCase();
|
||||||
(drama) =>
|
if (aliases.any(name.contains)) return category;
|
||||||
drama.category.toLowerCase().contains(categoryName) ||
|
}
|
||||||
drama.genre.toLowerCase().contains(categoryName),
|
return null;
|
||||||
)
|
}
|
||||||
.toList(growable: false);
|
|
||||||
return matched.isEmpty ? dramas : matched;
|
List<Drama> _dramasFor(
|
||||||
|
HomePrimaryTab tab,
|
||||||
|
String? tag,
|
||||||
|
List<HomeGridCategoryShortcut> shortcuts,
|
||||||
|
) {
|
||||||
|
Iterable<Drama> source = widget.feedController.dramas;
|
||||||
|
if (tab == HomePrimaryTab.costume || tab == HomePrimaryTab.community) {
|
||||||
|
final categoryName = shortcuts
|
||||||
|
.firstWhere((shortcut) => shortcut.tab == tab)
|
||||||
|
.categoryName
|
||||||
|
.toLowerCase();
|
||||||
|
if (categoryName.isEmpty) return const [];
|
||||||
|
source = source.where(
|
||||||
|
(drama) =>
|
||||||
|
drama.category.toLowerCase().contains(categoryName) ||
|
||||||
|
drama.genre.toLowerCase().contains(categoryName),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (tag != null) {
|
||||||
|
source = source.where((drama) => matchesHomeTag(drama, tag));
|
||||||
|
}
|
||||||
|
final dramas = source.toList(growable: false);
|
||||||
|
switch (tab) {
|
||||||
|
case HomePrimaryTab.newReleases:
|
||||||
|
return [...dramas]..sort((a, b) {
|
||||||
|
final left = publishedAtForDrama(a);
|
||||||
|
final right = publishedAtForDrama(b);
|
||||||
|
if (left == null && right == null) return b.id.compareTo(a.id);
|
||||||
|
if (left == null) return 1;
|
||||||
|
if (right == null) return -1;
|
||||||
|
return right.compareTo(left);
|
||||||
|
});
|
||||||
|
case HomePrimaryTab.ranking:
|
||||||
|
return [...dramas]..sort((a, b) => b.viewCount.compareTo(a.viewCount));
|
||||||
|
case HomePrimaryTab.featured:
|
||||||
|
case HomePrimaryTab.categories:
|
||||||
|
case HomePrimaryTab.costume:
|
||||||
|
case HomePrimaryTab.community:
|
||||||
|
return dramas;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _emptyState(AppLocalizations l10n) {
|
Widget _emptyState(AppLocalizations l10n) {
|
||||||
|
|||||||
@@ -20,13 +20,11 @@ class HomeGridCategoryShortcut {
|
|||||||
const HomeGridCategoryShortcut({
|
const HomeGridCategoryShortcut({
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.categoryName,
|
required this.categoryName,
|
||||||
required this.categoryId,
|
|
||||||
required this.tab,
|
required this.tab,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String label;
|
final String label;
|
||||||
final String categoryName;
|
final String categoryName;
|
||||||
final String categoryId;
|
|
||||||
final HomePrimaryTab tab;
|
final HomePrimaryTab tab;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,15 +47,15 @@ class HomeGridHeader extends StatelessWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
required this.callbacks,
|
required this.callbacks,
|
||||||
required this.categories,
|
required this.categories,
|
||||||
required this.selectedIndex,
|
required this.selectedPrimary,
|
||||||
required this.onSectionSelected,
|
required this.onPrimarySelected,
|
||||||
this.walletBadge,
|
this.walletBadge,
|
||||||
});
|
});
|
||||||
|
|
||||||
final HomeGridCallbacks callbacks;
|
final HomeGridCallbacks callbacks;
|
||||||
final List<HomeGridCategoryShortcut> categories;
|
final List<HomeGridCategoryShortcut> categories;
|
||||||
final int selectedIndex;
|
final HomePrimaryTab selectedPrimary;
|
||||||
final ValueChanged<int> onSectionSelected;
|
final ValueChanged<HomePrimaryTab> onPrimarySelected;
|
||||||
final int? walletBadge;
|
final int? walletBadge;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -69,7 +67,7 @@ class HomeGridHeader extends StatelessWidget {
|
|||||||
mainAxisAlignment: MainAxisAlignment.start,
|
mainAxisAlignment: MainAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
_searchRow(l10n),
|
_searchRow(l10n),
|
||||||
_primaryRow(),
|
_primaryRow(l10n),
|
||||||
const SizedBox(height: AppDimens.homeSecondaryGridGap),
|
const SizedBox(height: AppDimens.homeSecondaryGridGap),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -227,73 +225,7 @@ class HomeGridHeader extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _primaryRow() {
|
Widget _primaryRow(AppLocalizations l10n) {
|
||||||
return _CategoryBar(
|
|
||||||
categories: categories,
|
|
||||||
selectedIndex: selectedIndex,
|
|
||||||
onSectionSelected: onSectionSelected,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _CategoryBar extends StatefulWidget {
|
|
||||||
const _CategoryBar({
|
|
||||||
required this.categories,
|
|
||||||
required this.selectedIndex,
|
|
||||||
required this.onSectionSelected,
|
|
||||||
});
|
|
||||||
|
|
||||||
final List<HomeGridCategoryShortcut> categories;
|
|
||||||
final int selectedIndex;
|
|
||||||
final ValueChanged<int> onSectionSelected;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_CategoryBar> createState() => _CategoryBarState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _CategoryBarState extends State<_CategoryBar> {
|
|
||||||
final List<GlobalKey> _itemKeys = [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_syncKeys();
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(_CategoryBar oldWidget) {
|
|
||||||
super.didUpdateWidget(oldWidget);
|
|
||||||
if (oldWidget.categories.length != widget.categories.length) {
|
|
||||||
_syncKeys();
|
|
||||||
}
|
|
||||||
if (oldWidget.selectedIndex != widget.selectedIndex ||
|
|
||||||
oldWidget.categories.length != widget.categories.length) {
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _syncKeys() {
|
|
||||||
_itemKeys
|
|
||||||
..clear()
|
|
||||||
..addAll(List.generate(widget.categories.length, (_) => GlobalKey()));
|
|
||||||
}
|
|
||||||
|
|
||||||
void _revealSelected() {
|
|
||||||
final index = widget.selectedIndex;
|
|
||||||
if (!mounted || index < 0 || index >= _itemKeys.length) return;
|
|
||||||
final target = _itemKeys[index].currentContext;
|
|
||||||
if (target == null) return;
|
|
||||||
Scrollable.ensureVisible(
|
|
||||||
target,
|
|
||||||
alignment: 0.5,
|
|
||||||
duration: AppDimens.homePrimaryTabAnimationDuration,
|
|
||||||
curve: Curves.easeOut,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return SingleChildScrollView(
|
return SingleChildScrollView(
|
||||||
key: const Key('home-primary-sections'),
|
key: const Key('home-primary-sections'),
|
||||||
scrollDirection: Axis.horizontal,
|
scrollDirection: Axis.horizontal,
|
||||||
@@ -302,29 +234,60 @@ class _CategoryBarState extends State<_CategoryBar> {
|
|||||||
),
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisAlignment: MainAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
for (var index = 0; index < widget.categories.length; index++)
|
_primaryItem(
|
||||||
_item(index),
|
key: const Key('home-section-featured'),
|
||||||
|
label: l10n.homeSectionFeatured,
|
||||||
|
tab: HomePrimaryTab.featured,
|
||||||
|
),
|
||||||
|
_primaryItem(
|
||||||
|
key: const Key('home-section-new'),
|
||||||
|
label: l10n.homeSectionNew,
|
||||||
|
tab: HomePrimaryTab.newReleases,
|
||||||
|
),
|
||||||
|
_primaryItem(
|
||||||
|
key: const Key('home-section-categories'),
|
||||||
|
label: l10n.homeSectionCategories,
|
||||||
|
tab: HomePrimaryTab.categories,
|
||||||
|
),
|
||||||
|
_primaryItem(
|
||||||
|
key: const Key('home-section-ranking'),
|
||||||
|
label: l10n.homeSectionRanking,
|
||||||
|
tab: HomePrimaryTab.ranking,
|
||||||
|
),
|
||||||
|
for (final category in categories)
|
||||||
|
_primaryItem(
|
||||||
|
key: Key(
|
||||||
|
category.categoryName.isEmpty
|
||||||
|
? 'home-section-${category.tab.name}'
|
||||||
|
: 'home-section-category-${category.categoryName}',
|
||||||
|
),
|
||||||
|
label: category.label,
|
||||||
|
tab: category.tab,
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _item(int index) {
|
Widget _primaryItem({
|
||||||
final category = widget.categories[index];
|
required Key key,
|
||||||
final selected = widget.selectedIndex == index;
|
required String label,
|
||||||
|
required HomePrimaryTab tab,
|
||||||
|
}) {
|
||||||
|
final selected = selectedPrimary == tab;
|
||||||
return InkWell(
|
return InkWell(
|
||||||
key: _itemKeys[index],
|
key: key,
|
||||||
onTap: () => widget.onSectionSelected(index),
|
onTap: () => onPrimarySelected(tab),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
key: Key('home-section-category-${category.categoryName}'),
|
|
||||||
padding: const EdgeInsets.only(right: AppDimens.homePrimaryCategoryGap),
|
padding: const EdgeInsets.only(right: AppDimens.homePrimaryCategoryGap),
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
height: AppDimens.homePrimaryRowHeight,
|
height: AppDimens.homePrimaryRowHeight,
|
||||||
child: Align(
|
child: Align(
|
||||||
alignment: Alignment.bottomLeft,
|
alignment: Alignment.bottomLeft,
|
||||||
child: AnimatedDefaultTextStyle(
|
child: AnimatedDefaultTextStyle(
|
||||||
key: Key('home-primary-label-${category.categoryId}'),
|
key: Key('home-primary-label-${tab.name}'),
|
||||||
duration: AppDimens.homePrimaryTabAnimationDuration,
|
duration: AppDimens.homePrimaryTabAnimationDuration,
|
||||||
curve: Curves.easeOut,
|
curve: Curves.easeOut,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
@@ -337,7 +300,7 @@ class _CategoryBarState extends State<_CategoryBar> {
|
|||||||
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
|
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
|
||||||
letterSpacing: 0,
|
letterSpacing: 0,
|
||||||
),
|
),
|
||||||
child: Text(category.label, textAlign: TextAlign.left),
|
child: Text(label, textAlign: TextAlign.left),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -82,11 +82,7 @@ class MineContinueWatching extends StatelessWidget {
|
|||||||
const SizedBox(width: AppDimens.spaceMd),
|
const SizedBox(width: AppDimens.spaceMd),
|
||||||
itemBuilder: (_, index) {
|
itemBuilder: (_, index) {
|
||||||
final record = visible[index];
|
final record = visible[index];
|
||||||
return _card(
|
return _card(l10n, record);
|
||||||
l10n,
|
|
||||||
record,
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -94,8 +90,8 @@ class MineContinueWatching extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _card(AppLocalizations l10n, WatchProgress record, String languageCode) {
|
Widget _card(AppLocalizations l10n, WatchProgress record) {
|
||||||
final title = record.localizedTitle(languageCode).trim();
|
final title = record.dramaTitle?.trim() ?? '';
|
||||||
final episode = record.episodeNumber;
|
final episode = record.episodeNumber;
|
||||||
final hasProgress = record.duration > Duration.zero;
|
final hasProgress = record.duration > Duration.zero;
|
||||||
return SizedBox(
|
return SizedBox(
|
||||||
|
|||||||
@@ -192,8 +192,6 @@ class _NewReleasesPageState extends State<NewReleasesPage> {
|
|||||||
),
|
),
|
||||||
PagedLoadFooter(
|
PagedLoadFooter(
|
||||||
loading: pager.loading,
|
loading: pager.loading,
|
||||||
hasMore: pager.hasMore,
|
|
||||||
hasItems: visible.isNotEmpty,
|
|
||||||
loadMoreKey: const Key(
|
loadMoreKey: const Key(
|
||||||
'new-releases-load-more',
|
'new-releases-load-more',
|
||||||
),
|
),
|
||||||
@@ -432,7 +430,7 @@ class _NewReleasesPageState extends State<NewReleasesPage> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 6),
|
||||||
Text(
|
Text(
|
||||||
drama.title,
|
drama.title,
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
|
|||||||
@@ -171,17 +171,6 @@ class _NoticesPageState extends State<NoticesPage> {
|
|||||||
label: Text(l10n.retry),
|
label: Text(l10n.retry),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (_controller.notices.isNotEmpty && !_controller.hasMore) {
|
|
||||||
return Padding(
|
|
||||||
key: const Key('paged-list-no-more'),
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
||||||
child: Text(
|
|
||||||
l10n.noMoreItems,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,24 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../../core/data/models/drama.dart';
|
import '../../core/data/models/drama.dart';
|
||||||
|
import '../../core/data/services/auth_controller.dart';
|
||||||
|
import '../../core/widgets/auth_gate.dart';
|
||||||
|
|
||||||
/// 评论列表与非付费互动均支持设备身份,不再把登录作为入口前置条件。
|
/// 评论入口统一登录闸:登录成功且页面仍存在时再打开评论面板。
|
||||||
Future<void> openComments(
|
Future<void> openCommentsWithAuth(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
Drama drama, {
|
Drama drama, {
|
||||||
required Future<void> Function(BuildContext context, Drama drama) show,
|
required Future<void> Function(BuildContext context, Drama drama) show,
|
||||||
}) async {
|
}) async {
|
||||||
|
final auth = context.read<AuthController>();
|
||||||
|
if (auth.isSignedIn) {
|
||||||
|
await show(context, drama);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await ensureSignedIn(context);
|
||||||
|
if (!context.mounted || !auth.isSignedIn) return;
|
||||||
await show(context, drama);
|
await show(context, drama);
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,6 @@ class PlayerBinding {
|
|||||||
required PlaybackPositionCache positionCache,
|
required PlaybackPositionCache positionCache,
|
||||||
WalletController? wallet,
|
WalletController? wallet,
|
||||||
DownloadController? downloads,
|
DownloadController? downloads,
|
||||||
bool Function()? isSignedIn,
|
|
||||||
}) => PlayerLogic(
|
}) => PlayerLogic(
|
||||||
history: history,
|
history: history,
|
||||||
playback: playback,
|
playback: playback,
|
||||||
@@ -23,6 +22,5 @@ class PlayerBinding {
|
|||||||
pictureInPicture: AndroidPictureInPicture(),
|
pictureInPicture: AndroidPictureInPicture(),
|
||||||
wallet: wallet,
|
wallet: wallet,
|
||||||
downloads: downloads,
|
downloads: downloads,
|
||||||
isSignedIn: isSignedIn,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2,14 +2,12 @@
|
|||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:video_player/video_player.dart';
|
import 'package:video_player/video_player.dart';
|
||||||
import 'package:flutter/scheduler.dart';
|
import 'package:flutter/scheduler.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../../core/data/models/drama.dart';
|
import '../../core/data/models/drama.dart';
|
||||||
import '../../core/data/models/episode_stats.dart';
|
|
||||||
import '../../core/data/models/play_ticket.dart';
|
import '../../core/data/models/play_ticket.dart';
|
||||||
import '../../core/data/models/watch_progress.dart';
|
import '../../core/data/models/watch_progress.dart';
|
||||||
import '../../core/data/models/player_port.dart';
|
import '../../core/data/models/player_port.dart';
|
||||||
@@ -52,13 +50,9 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
this.downloads,
|
this.downloads,
|
||||||
PlaybackPositionCache? positionCache,
|
PlaybackPositionCache? positionCache,
|
||||||
Future<void> Function()? waitForFrame,
|
Future<void> Function()? waitForFrame,
|
||||||
DateTime Function()? clock,
|
|
||||||
bool Function()? isSignedIn,
|
|
||||||
}) : positionCache = positionCache ?? PlaybackPositionCache(),
|
}) : positionCache = positionCache ?? PlaybackPositionCache(),
|
||||||
_waitForFrame =
|
_waitForFrame =
|
||||||
waitForFrame ?? (() => WidgetsBinding.instance.endOfFrame),
|
waitForFrame ?? (() => WidgetsBinding.instance.endOfFrame);
|
||||||
_clock = clock ?? DateTime.now,
|
|
||||||
_isSignedIn = isSignedIn ?? (() => true);
|
|
||||||
|
|
||||||
final WatchHistoryRepository history;
|
final WatchHistoryRepository history;
|
||||||
final PlaybackRepository playback;
|
final PlaybackRepository playback;
|
||||||
@@ -67,8 +61,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
final DownloadController? downloads;
|
final DownloadController? downloads;
|
||||||
final PlaybackPositionCache positionCache;
|
final PlaybackPositionCache positionCache;
|
||||||
final Future<void> Function() _waitForFrame;
|
final Future<void> Function() _waitForFrame;
|
||||||
final DateTime Function() _clock;
|
|
||||||
final bool Function() _isSignedIn;
|
|
||||||
|
|
||||||
late PageController pages;
|
late PageController pages;
|
||||||
late PlaybackQueue queue;
|
late PlaybackQueue queue;
|
||||||
@@ -101,25 +93,13 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
String selectedQuality = 'AUTO';
|
String selectedQuality = 'AUTO';
|
||||||
Duration? _qualitySeek;
|
Duration? _qualitySeek;
|
||||||
int pageRequest = 0;
|
int pageRequest = 0;
|
||||||
int? _pendingSelectionIndex;
|
|
||||||
int? _pendingSelectionRevision;
|
|
||||||
Future<void>? _selectionDrain;
|
|
||||||
bool muted = false;
|
bool muted = false;
|
||||||
double playbackSpeed = 1.0;
|
double playbackSpeed = 1.0;
|
||||||
bool stoppedAtFeedEnd = false;
|
bool stoppedAtFeedEnd = false;
|
||||||
Duration episodeStatsTtl = const Duration(seconds: 60);
|
|
||||||
ValueChanged<EpisodeStats>? onEpisodeStatsUpdated;
|
|
||||||
VideoPlayerPort? scrubbingPlayer;
|
VideoPlayerPort? scrubbingPlayer;
|
||||||
bool pip = false;
|
bool pip = false;
|
||||||
bool pipPreparing = false;
|
bool pipPreparing = false;
|
||||||
final Map<String, int> pickedEpisode = {};
|
final Map<String, int> pickedEpisode = {};
|
||||||
final Set<String> _unlockedEpisodeIds = {};
|
|
||||||
final Map<String, EpisodeStats> _episodeStats = {};
|
|
||||||
final Map<String, DateTime> _episodeStatsFetchedAt = {};
|
|
||||||
final Map<String, Future<void>> _episodeStatsInFlight = {};
|
|
||||||
final Map<String, int> _episodeStatsRevision = {};
|
|
||||||
final Map<String, int> _dramaStatsRevision = {};
|
|
||||||
final Map<String, int> _dramaFavoriteCounts = {};
|
|
||||||
|
|
||||||
/// 解锁中的集 id 与失败文案;空表示没有进行中的解锁。
|
/// 解锁中的集 id 与失败文案;空表示没有进行中的解锁。
|
||||||
String? unlockingEpisodeId;
|
String? unlockingEpisodeId;
|
||||||
@@ -183,10 +163,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
EpisodeStats? episodeStats(String episodeId) => _episodeStats[episodeId];
|
|
||||||
|
|
||||||
int? dramaFavoriteCount(String dramaId) => _dramaFavoriteCounts[dramaId];
|
|
||||||
|
|
||||||
void notify() {
|
void notify() {
|
||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
}
|
}
|
||||||
@@ -212,7 +188,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
void start({
|
void start({
|
||||||
required PlayerFactory factory,
|
required PlayerFactory factory,
|
||||||
required PlaybackCoordinator coordinator,
|
required PlaybackCoordinator coordinator,
|
||||||
bool initialUserWantsPlay = true,
|
|
||||||
}) {
|
}) {
|
||||||
_started = true;
|
_started = true;
|
||||||
_sessionFactory = factory;
|
_sessionFactory = factory;
|
||||||
@@ -230,48 +205,7 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
session.setRouteVisible(false);
|
session.setRouteVisible(false);
|
||||||
}
|
}
|
||||||
unawaited(loadResumePoint());
|
unawaited(loadResumePoint());
|
||||||
unawaited(
|
unawaited(selectEpisode(initialIndex));
|
||||||
selectEpisode(
|
|
||||||
initialIndex,
|
|
||||||
userWantsPlay: initialUserWantsPlay ? null : false,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 独立播放页覆盖首页时只暂停并保存进度,首页 session 与 controller 保持存活。
|
|
||||||
Future<void> pauseForFullPlayer() async {
|
|
||||||
if (!_started) return;
|
|
||||||
_logFeedHandoff('pause');
|
|
||||||
cancelScrub();
|
|
||||||
await session.pauseForRouteHandoff();
|
|
||||||
_logFeedHandoff('paused');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 独立播放页关闭并恢复首页路由后,等原生播放器实际恢复再结束交接。
|
|
||||||
Future<void> resumeAfterFullPlayer() async {
|
|
||||||
if (!_started) return;
|
|
||||||
_logFeedHandoff('resume');
|
|
||||||
if (visibleIndices.isNotEmpty) {
|
|
||||||
await session.resumeForRouteHandoff();
|
|
||||||
} else {
|
|
||||||
session.setRouteVisible(false);
|
|
||||||
await session.playbackSettled;
|
|
||||||
}
|
|
||||||
_logFeedHandoff('resumed');
|
|
||||||
}
|
|
||||||
|
|
||||||
void _logFeedHandoff(String phase) {
|
|
||||||
if (!kDebugMode) return;
|
|
||||||
final player = session.active;
|
|
||||||
final video = player is VideoPlayerPort ? player : null;
|
|
||||||
debugPrint(
|
|
||||||
'[feed-session] phase=$phase session=${identityHashCode(session)} '
|
|
||||||
'index=${session.currentIndex} episode=${session.currentEpisode.id} '
|
|
||||||
'controller=${video == null ? '-' : identityHashCode(video.controller)} '
|
|
||||||
'user=${session.userWantsPlay} routeVisible=${session.debugRouteVisible} '
|
|
||||||
'appResumed=${session.debugAppResumed} overlayOpen=${session.debugOverlayOpen} '
|
|
||||||
'live=${session.livePlayerCount}',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 串行替换首页 feed 队列;频道变化时重置到第 1 个,刷新时尽量保留当前剧。
|
/// 串行替换首页 feed 队列;频道变化时重置到第 1 个,刷新时尽量保留当前剧。
|
||||||
@@ -304,16 +238,11 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
episodes: sessionEpisodes,
|
episodes: sessionEpisodes,
|
||||||
factory: factory,
|
factory: factory,
|
||||||
// 地址只由后端下发(票据或详情里的免费集签名地址),拿不到地址即视为锁定
|
// 地址只由后端下发(票据或详情里的免费集签名地址),拿不到地址即视为锁定
|
||||||
canPlay: (episode) =>
|
canPlay: (episode) => episode.videoUrl.isNotEmpty,
|
||||||
episode.videoUrl.isNotEmpty && !isEpisodeLocked(episode),
|
|
||||||
prepare: preparePlayer,
|
prepare: preparePlayer,
|
||||||
activate: activatePlayer,
|
activate: activatePlayer,
|
||||||
coordinator: coordinator,
|
coordinator: coordinator,
|
||||||
waitForFrame: _waitForFrame,
|
waitForFrame: _waitForFrame,
|
||||||
owner: homeMode ? PlaybackSessionOwner.home : PlaybackSessionOwner.player,
|
|
||||||
dramaIdAt: (index) => index >= 0 && index < queue.length
|
|
||||||
? queue.entryAt(index).drama.id
|
|
||||||
: null,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -370,7 +299,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
session.remapCurrentIndex(
|
session.remapCurrentIndex(
|
||||||
keepIndex,
|
keepIndex,
|
||||||
preloadIndex: nextVisibleIndex(keepIndex),
|
preloadIndex: nextVisibleIndex(keepIndex),
|
||||||
previousIndex: previousVisibleIndex(keepIndex),
|
|
||||||
);
|
);
|
||||||
_jumpToFeedPage(keepIndex);
|
_jumpToFeedPage(keepIndex);
|
||||||
_notifyAfterFrameIfNeeded();
|
_notifyAfterFrameIfNeeded();
|
||||||
@@ -499,7 +427,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
final localPath = await downloads?.findLocalPath(episode.id);
|
final localPath = await downloads?.findLocalPath(episode.id);
|
||||||
if (request != pageRequest) return false;
|
if (request != pageRequest) return false;
|
||||||
if (localPath != null) {
|
if (localPath != null) {
|
||||||
_unlockedEpisodeIds.add(episode.id);
|
|
||||||
blockedTicket = null;
|
blockedTicket = null;
|
||||||
blockedEpisodeId = null;
|
blockedEpisodeId = null;
|
||||||
qualities = const [];
|
qualities = const [];
|
||||||
@@ -524,14 +451,12 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
final playUrl = preferred ?? ticket.playUrl;
|
final playUrl = preferred ?? ticket.playUrl;
|
||||||
if (preferred == null) selectedQuality = 'AUTO';
|
if (preferred == null) selectedQuality = 'AUTO';
|
||||||
if (ticket.accessible && playUrl.isNotEmpty) {
|
if (ticket.accessible && playUrl.isNotEmpty) {
|
||||||
_unlockedEpisodeIds.add(episode.id);
|
|
||||||
// 签名地址原样写回,不做任何拼接/改写(AppConfig.mediaUrl 只补 host)
|
// 签名地址原样写回,不做任何拼接/改写(AppConfig.mediaUrl 只补 host)
|
||||||
sessionEpisodes[index] = episode.withVideoUrl(
|
sessionEpisodes[index] = episode.withVideoUrl(
|
||||||
playUrl,
|
playUrl,
|
||||||
likeCount: ticket.likeCount,
|
likeCount: ticket.likeCount,
|
||||||
commentCount: ticket.commentCount,
|
commentCount: ticket.commentCount,
|
||||||
thumbnailsUrl: ticket.thumbnailsUrl,
|
thumbnailsUrl: ticket.thumbnailsUrl,
|
||||||
posterUrl: ticket.posterUrl,
|
|
||||||
);
|
);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -541,7 +466,7 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
} catch (exception) {
|
} catch (exception) {
|
||||||
if (request != pageRequest) return false;
|
if (request != pageRequest) return false;
|
||||||
// 详情里已有可用地址(免费集)时降级继续,避免票据服务抖动就完全看不了
|
// 详情里已有可用地址(免费集)时降级继续,避免票据服务抖动就完全看不了
|
||||||
if (episode.videoUrl.isNotEmpty && !isEpisodeLocked(episode)) {
|
if (episode.videoUrl.isNotEmpty) {
|
||||||
ticketError = null;
|
ticketError = null;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -555,179 +480,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 当前集激活后刷新轻量互动计数;同集命中 TTL 或已有请求时不重复发请求。
|
|
||||||
Future<void> refreshEpisodeStats(int index) {
|
|
||||||
if (_disposed || index < 0 || index >= sessionEpisodes.length) {
|
|
||||||
return Future<void>.value();
|
|
||||||
}
|
|
||||||
final episodeId = sessionEpisodes[index].id;
|
|
||||||
final cached = _episodeStats[episodeId];
|
|
||||||
final fetchedAt = _episodeStatsFetchedAt[episodeId];
|
|
||||||
if (cached != null &&
|
|
||||||
fetchedAt != null &&
|
|
||||||
_clock().difference(fetchedAt) < episodeStatsTtl) {
|
|
||||||
_logEpisodeStatsRefresh(episodeId, cached: true);
|
|
||||||
onEpisodeStatsUpdated?.call(cached);
|
|
||||||
return Future<void>.value();
|
|
||||||
}
|
|
||||||
final inFlight = _episodeStatsInFlight[episodeId];
|
|
||||||
if (inFlight != null) {
|
|
||||||
_logEpisodeStatsRefresh(episodeId, cached: true, inFlight: true);
|
|
||||||
return inFlight;
|
|
||||||
}
|
|
||||||
_logEpisodeStatsRefresh(episodeId, cached: false);
|
|
||||||
final expectedDramaId = index < queue.length
|
|
||||||
? queue.entryAt(index).drama.id
|
|
||||||
: '';
|
|
||||||
final episodeRevision = _episodeStatsRevision[episodeId] ?? 0;
|
|
||||||
final dramaRevision = _dramaStatsRevision[expectedDramaId] ?? 0;
|
|
||||||
late final Future<void> request;
|
|
||||||
request =
|
|
||||||
_fetchEpisodeStats(
|
|
||||||
episodeId,
|
|
||||||
expectedDramaId: expectedDramaId,
|
|
||||||
episodeRevision: episodeRevision,
|
|
||||||
dramaRevision: dramaRevision,
|
|
||||||
).whenComplete(() {
|
|
||||||
if (identical(_episodeStatsInFlight[episodeId], request)) {
|
|
||||||
_episodeStatsInFlight.remove(episodeId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
_episodeStatsInFlight[episodeId] = request;
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _fetchEpisodeStats(
|
|
||||||
String episodeId, {
|
|
||||||
required String expectedDramaId,
|
|
||||||
required int episodeRevision,
|
|
||||||
required int dramaRevision,
|
|
||||||
}) async {
|
|
||||||
try {
|
|
||||||
final fetched = await playback.episodeStats(episodeId);
|
|
||||||
if (_disposed) return;
|
|
||||||
if ((_episodeStatsRevision[episodeId] ?? 0) != episodeRevision ||
|
|
||||||
(_dramaStatsRevision[expectedDramaId] ?? 0) != dramaRevision) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint(
|
|
||||||
'[player] phase=episode-stats-discarded episodeId=$episodeId '
|
|
||||||
'reason=local-state-newer',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final stats = fetched.copyWith(
|
|
||||||
dramaId: fetched.dramaId.isEmpty ? expectedDramaId : fetched.dramaId,
|
|
||||||
);
|
|
||||||
_episodeStats[episodeId] = stats;
|
|
||||||
_episodeStatsFetchedAt[episodeId] = _clock();
|
|
||||||
if (stats.dramaId.isNotEmpty) {
|
|
||||||
_dramaFavoriteCounts[stats.dramaId] = stats.favoriteCount;
|
|
||||||
}
|
|
||||||
final episodeIndex = sessionEpisodes.indexWhere(
|
|
||||||
(episode) => episode.id == episodeId,
|
|
||||||
);
|
|
||||||
if (episodeIndex >= 0) {
|
|
||||||
sessionEpisodes[episodeIndex] = sessionEpisodes[episodeIndex].withStats(
|
|
||||||
likeCount: stats.likeCount,
|
|
||||||
commentCount: stats.commentCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
onEpisodeStatsUpdated?.call(stats);
|
|
||||||
notify();
|
|
||||||
} catch (_) {
|
|
||||||
// 统计接口只负责校准计数,失败时保留播放与旧值。
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _logEpisodeStatsRefresh(
|
|
||||||
String episodeId, {
|
|
||||||
required bool cached,
|
|
||||||
bool inFlight = false,
|
|
||||||
}) {
|
|
||||||
if (!kDebugMode) return;
|
|
||||||
debugPrint(
|
|
||||||
'[player] phase=episode-stats-refresh episodeId=$episodeId '
|
|
||||||
'cached=${cached ? 1 : 0}${inFlight ? ' inFlight=1' : ''}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 点赞成功后同步本地统计快照,避免切回时被旧缓存覆盖。
|
|
||||||
void applyEpisodeLikeState(
|
|
||||||
String episodeId, {
|
|
||||||
required bool liked,
|
|
||||||
required int likeCount,
|
|
||||||
}) {
|
|
||||||
_episodeStatsRevision.update(
|
|
||||||
episodeId,
|
|
||||||
(value) => value + 1,
|
|
||||||
ifAbsent: () => 1,
|
|
||||||
);
|
|
||||||
final stats = _episodeStats[episodeId];
|
|
||||||
if (stats != null) {
|
|
||||||
_episodeStats[episodeId] = stats.copyWith(
|
|
||||||
liked: liked,
|
|
||||||
likeCount: likeCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final index = sessionEpisodes.indexWhere(
|
|
||||||
(episode) => episode.id == episodeId,
|
|
||||||
);
|
|
||||||
if (index >= 0) {
|
|
||||||
sessionEpisodes[index] = sessionEpisodes[index].withStats(
|
|
||||||
likeCount: likeCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 评论面板关闭后同步评论数。
|
|
||||||
void applyEpisodeCommentCount(String episodeId, int commentCount) {
|
|
||||||
_episodeStatsRevision.update(
|
|
||||||
episodeId,
|
|
||||||
(value) => value + 1,
|
|
||||||
ifAbsent: () => 1,
|
|
||||||
);
|
|
||||||
final stats = _episodeStats[episodeId];
|
|
||||||
if (stats != null) {
|
|
||||||
_episodeStats[episodeId] = stats.copyWith(commentCount: commentCount);
|
|
||||||
}
|
|
||||||
final index = sessionEpisodes.indexWhere(
|
|
||||||
(episode) => episode.id == episodeId,
|
|
||||||
);
|
|
||||||
if (index >= 0) {
|
|
||||||
sessionEpisodes[index] = sessionEpisodes[index].withStats(
|
|
||||||
commentCount: commentCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 收藏成功时同时修正剧级计数和所有已缓存的同剧互动状态。
|
|
||||||
void applyDramaFavoriteState(
|
|
||||||
String dramaId, {
|
|
||||||
required bool favorited,
|
|
||||||
int? favoriteCount,
|
|
||||||
}) {
|
|
||||||
_dramaStatsRevision.update(
|
|
||||||
dramaId,
|
|
||||||
(value) => value + 1,
|
|
||||||
ifAbsent: () => 1,
|
|
||||||
);
|
|
||||||
if (favoriteCount != null) {
|
|
||||||
_dramaFavoriteCounts[dramaId] = favoriteCount;
|
|
||||||
}
|
|
||||||
for (final entry in _episodeStats.entries.toList()) {
|
|
||||||
final stats = entry.value;
|
|
||||||
if (stats.dramaId != dramaId) continue;
|
|
||||||
_episodeStats[entry.key] = stats.copyWith(
|
|
||||||
favorited: favorited,
|
|
||||||
favoriteCount: favoriteCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
String _fileUrl(String path) =>
|
String _fileUrl(String path) =>
|
||||||
path.startsWith('file:') ? path : Uri.file(path).toString();
|
path.startsWith('file:') ? path : Uri.file(path).toString();
|
||||||
|
|
||||||
@@ -778,7 +530,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
if (done.isCompleted) return;
|
if (done.isCompleted) return;
|
||||||
if (value.hasError || !value.isBuffering) done.complete();
|
if (value.hasError || !value.isBuffering) done.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
controller.addListener(onChange);
|
controller.addListener(onChange);
|
||||||
try {
|
try {
|
||||||
await done.future.timeout(const Duration(seconds: 4));
|
await done.future.timeout(const Duration(seconds: 4));
|
||||||
@@ -800,10 +551,7 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
/// 金币解锁当前集;成功后强制刷新票据并直接起播。
|
/// 金币解锁当前集;成功后强制刷新票据并直接起播。
|
||||||
Future<bool> unlockEpisode(int index) async {
|
Future<bool> unlockEpisode(int index) async {
|
||||||
final service = wallet;
|
final service = wallet;
|
||||||
if (service == null ||
|
if (service == null || index < 0 || index >= sessionEpisodes.length) {
|
||||||
!_isSignedIn() ||
|
|
||||||
index < 0 ||
|
|
||||||
index >= sessionEpisodes.length) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
final episode = sessionEpisodes[index];
|
final episode = sessionEpisodes[index];
|
||||||
@@ -816,10 +564,9 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
unlockError = service.unlockError;
|
unlockError = service.unlockError;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
_unlockedEpisodeIds.add(episode.id);
|
|
||||||
final ready = await ensureTicket(index, forceRefresh: true);
|
final ready = await ensureTicket(index, forceRefresh: true);
|
||||||
if (ready) {
|
if (ready) {
|
||||||
await _selectVisible(index);
|
await session.select(index, preloadIndex: nextVisibleIndex(index));
|
||||||
}
|
}
|
||||||
return ready;
|
return ready;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -1202,43 +949,7 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 翻页入口使用 single-flight:执行中的切集不被重复排队,只保留最新目标。
|
Future<void> selectEpisode(int index, {int? revision}) async {
|
||||||
Future<void> requestEpisodeSelection(int index, {int? revision}) {
|
|
||||||
if (_disposed || index < 0 || index >= sessionEpisodes.length) {
|
|
||||||
return Future<void>.value();
|
|
||||||
}
|
|
||||||
_pendingSelectionIndex = index;
|
|
||||||
_pendingSelectionRevision = revision;
|
|
||||||
return _selectionDrain ??= _drainEpisodeSelections();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _drainEpisodeSelections() async {
|
|
||||||
try {
|
|
||||||
while (!_disposed) {
|
|
||||||
final index = _pendingSelectionIndex;
|
|
||||||
if (index == null) break;
|
|
||||||
final revision = _pendingSelectionRevision;
|
|
||||||
_pendingSelectionIndex = null;
|
|
||||||
_pendingSelectionRevision = null;
|
|
||||||
await selectEpisode(index, revision: revision);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
_selectionDrain = null;
|
|
||||||
final index = _pendingSelectionIndex;
|
|
||||||
if (!_disposed && index != null) {
|
|
||||||
unawaited(
|
|
||||||
requestEpisodeSelection(index, revision: _pendingSelectionRevision),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> selectEpisode(
|
|
||||||
int index, {
|
|
||||||
int? revision,
|
|
||||||
bool? userWantsPlay,
|
|
||||||
}) async {
|
|
||||||
if (index < 0 || index >= sessionEpisodes.length) return;
|
|
||||||
final feedRevisionAtStart = revision ?? feedRevision;
|
final feedRevisionAtStart = revision ?? feedRevision;
|
||||||
final request = ++pageRequest;
|
final request = ++pageRequest;
|
||||||
cancelScrub();
|
cancelScrub();
|
||||||
@@ -1249,26 +960,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
!isMounted()) {
|
!isMounted()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final episode = sessionEpisodes[index];
|
|
||||||
if (isEpisodeLocked(episode)) {
|
|
||||||
blockedTicket = null;
|
|
||||||
blockedEpisodeId = episode.id;
|
|
||||||
ticketError = null;
|
|
||||||
await session.selectLocked(
|
|
||||||
index,
|
|
||||||
preloadIndex: nextVisibleIndex(index),
|
|
||||||
previousIndex: previousVisibleIndex(index),
|
|
||||||
);
|
|
||||||
if (request != pageRequest ||
|
|
||||||
feedRevisionAtStart != feedRevision ||
|
|
||||||
!isMounted()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!_isSignedIn()) {
|
|
||||||
unawaited(refreshEpisodeStats(index));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 起播前先要票据:拿不到就不起播,交给三态 UI 提示(失败可重试)
|
// 起播前先要票据:拿不到就不起播,交给三态 UI 提示(失败可重试)
|
||||||
final ready = await ensureTicket(index);
|
final ready = await ensureTicket(index);
|
||||||
if (request != pageRequest ||
|
if (request != pageRequest ||
|
||||||
@@ -1276,30 +967,8 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
!isMounted()) {
|
!isMounted()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!ready) {
|
if (!ready && ticketError != null) return;
|
||||||
unawaited(refreshEpisodeStats(index));
|
await session.select(index, preloadIndex: nextVisibleIndex(index));
|
||||||
return;
|
|
||||||
}
|
|
||||||
await _selectVisible(index, userWantsPlay: userWantsPlay);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 收费集只有在本会话确认可播或解锁成功后才解除门禁。
|
|
||||||
bool isEpisodeLocked(Episode episode) {
|
|
||||||
return (episode.locked || !episode.isFree) &&
|
|
||||||
!_unlockedEpisodeIds.contains(episode.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 按可见队列选择一集,并预热上一集与下一集。
|
|
||||||
Future<void> _selectVisible(int index, {bool? userWantsPlay}) async {
|
|
||||||
await session.select(
|
|
||||||
index,
|
|
||||||
preloadIndex: nextVisibleIndex(index),
|
|
||||||
previousIndex: previousVisibleIndex(index),
|
|
||||||
userWantsPlay: userWantsPlay,
|
|
||||||
);
|
|
||||||
if (!_disposed && session.currentIndex == index) {
|
|
||||||
unawaited(refreshEpisodeStats(index));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int? nextVisibleIndex(int index) {
|
int? nextVisibleIndex(int index) {
|
||||||
@@ -1309,13 +978,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
: null;
|
: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 可见队列里当前集的上一集;已经是第一集时为空。
|
|
||||||
int? previousVisibleIndex(int index) {
|
|
||||||
final position = visibleIndices.indexOf(index);
|
|
||||||
if (position <= 0) return null;
|
|
||||||
return visibleIndices[position - 1];
|
|
||||||
}
|
|
||||||
|
|
||||||
bool get hasNextEpisode => nextVisibleIndex(session.currentIndex) != null;
|
bool get hasNextEpisode => nextVisibleIndex(session.currentIndex) != null;
|
||||||
|
|
||||||
Future<void> playNextEpisode() async {
|
Future<void> playNextEpisode() async {
|
||||||
@@ -1433,10 +1095,12 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
Drama drama,
|
Drama drama,
|
||||||
int index,
|
int index,
|
||||||
) async {
|
) async {
|
||||||
final route = Navigator.of(context).push(
|
session.setRouteVisible(false);
|
||||||
|
await session.playbackSettled;
|
||||||
|
await saveCurrentProgress();
|
||||||
|
if (!context.mounted) return;
|
||||||
|
await Navigator.of(context).push(
|
||||||
FadePageRoute<void>(
|
FadePageRoute<void>(
|
||||||
transitionDuration: Duration.zero,
|
|
||||||
reverseTransitionDuration: Duration.zero,
|
|
||||||
builder: (_) => PlayerPage(
|
builder: (_) => PlayerPage(
|
||||||
drama: drama,
|
drama: drama,
|
||||||
initialIndex: index,
|
initialIndex: index,
|
||||||
@@ -1445,14 +1109,7 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (kDebugMode) {
|
if (isMounted()) session.setRouteVisible(active);
|
||||||
debugPrint('[player-entry] phase=route-pushed source=watch-all ms=0');
|
|
||||||
}
|
|
||||||
unawaited(pauseForFullPlayer());
|
|
||||||
unawaited(saveCurrentProgress());
|
|
||||||
await route;
|
|
||||||
if (!isMounted()) return;
|
|
||||||
await resumeAfterFullPlayer();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> showEpisodes(BuildContext context) async {
|
Future<void> showEpisodes(BuildContext context) async {
|
||||||
|
|||||||
+150
-773
File diff suppressed because it is too large.
Load diff
@@ -65,11 +65,6 @@ extension _PlayerViewActions on _PlayerPageState {
|
|||||||
) async {
|
) async {
|
||||||
final wallet = logic.wallet;
|
final wallet = logic.wallet;
|
||||||
if (wallet == null) return;
|
if (wallet == null) return;
|
||||||
if (!context.read<AuthController>().isSignedIn &&
|
|
||||||
!await ensureSignedIn(context)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!context.mounted) return;
|
|
||||||
await showModalBottomSheet<bool>(
|
await showModalBottomSheet<bool>(
|
||||||
context: context,
|
context: context,
|
||||||
backgroundColor: AppColors.transparent,
|
backgroundColor: AppColors.transparent,
|
||||||
@@ -86,7 +81,7 @@ extension _PlayerViewActions on _PlayerPageState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> _unlockEpisode(BuildContext context, int index) async {
|
Future<bool> _unlockEpisode(BuildContext context, int index) async {
|
||||||
if (!context.read<AuthController>().isSignedIn) return false;
|
if (!await ensureSignedIn(context) || !context.mounted) return false;
|
||||||
final ok = await logic.unlockEpisode(index);
|
final ok = await logic.unlockEpisode(index);
|
||||||
if (ok || !context.mounted) return ok;
|
if (ok || !context.mounted) return ok;
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
@@ -104,53 +99,18 @@ extension _PlayerViewActions on _PlayerPageState {
|
|||||||
Episode episode, {
|
Episode episode, {
|
||||||
bool likeOnly = false,
|
bool likeOnly = false,
|
||||||
}) async {
|
}) async {
|
||||||
final busyBefore = interactions.isEpisodeBusy(episode.id);
|
|
||||||
final likedBefore = interactions.isEpisodeLiked(episode.id);
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint(
|
|
||||||
'[player-like] phase=toggle-start '
|
|
||||||
'episodeId=${episode.id} likeOnly=$likeOnly '
|
|
||||||
'busy=$busyBefore liked=$likedBefore',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
unawaited(context.read<Haptics>().lightImpact());
|
unawaited(context.read<Haptics>().lightImpact());
|
||||||
if (busyBefore || (likeOnly && likedBefore)) {
|
if (interactions.isEpisodeBusy(episode.id) ||
|
||||||
if (kDebugMode) {
|
(likeOnly && interactions.isEpisodeLiked(episode.id))) {
|
||||||
debugPrint(
|
return;
|
||||||
'[player-like] phase=toggle-skipped '
|
}
|
||||||
'episodeId=${episode.id} '
|
if (!await ensureSignedIn(context) || !context.mounted) return;
|
||||||
'reason=${busyBefore ? 'busy' : 'already-liked'}',
|
if (interactions.isEpisodeBusy(episode.id) ||
|
||||||
);
|
(likeOnly && interactions.isEpisodeLiked(episode.id))) {
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final result = await interactions.toggleEpisodeLike(episode.id);
|
final result = await interactions.toggleEpisodeLike(episode.id);
|
||||||
if (kDebugMode) {
|
if (result.isSuccess || !context.mounted) return;
|
||||||
debugPrint(
|
|
||||||
'[player-like] phase=toggle-result '
|
|
||||||
'episodeId=${episode.id} success=${result.isSuccess} '
|
|
||||||
'liked=${interactions.isEpisodeLiked(episode.id)} '
|
|
||||||
'count=${interactions.episodeLikeCount(episode.id)} '
|
|
||||||
'error=${result.errorMessage ?? '-'}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (result.isSuccess) {
|
|
||||||
final likeCount = interactions.episodeLikeCount(episode.id);
|
|
||||||
if (likeCount != null) {
|
|
||||||
logic.applyEpisodeLikeState(
|
|
||||||
episode.id,
|
|
||||||
liked: interactions.isEpisodeLiked(episode.id),
|
|
||||||
likeCount: likeCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_refreshLikeState();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!context.mounted) return;
|
|
||||||
if (result.errorCode == 200007) {
|
|
||||||
await ensureSignedIn(context);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
showCenteredToast(
|
showCenteredToast(
|
||||||
context,
|
context,
|
||||||
result.errorMessage ?? AppLocalizations.of(context)!.likeFailed,
|
result.errorMessage ?? AppLocalizations.of(context)!.likeFailed,
|
||||||
@@ -159,6 +119,7 @@ extension _PlayerViewActions on _PlayerPageState {
|
|||||||
|
|
||||||
Future<void> _toggleSave(BuildContext context, Drama drama) async {
|
Future<void> _toggleSave(BuildContext context, Drama drama) async {
|
||||||
final favorites = context.read<FavoriteController>();
|
final favorites = context.read<FavoriteController>();
|
||||||
|
if (!await ensureSignedIn(context) || !context.mounted) return;
|
||||||
unawaited(context.read<Haptics>().lightImpact());
|
unawaited(context.read<Haptics>().lightImpact());
|
||||||
final wasSaved = favorites.isSaved(drama.id);
|
final wasSaved = favorites.isSaved(drama.id);
|
||||||
final ok = await favorites.toggle(drama.id, card: drama);
|
final ok = await favorites.toggle(drama.id, card: drama);
|
||||||
@@ -166,14 +127,10 @@ extension _PlayerViewActions on _PlayerPageState {
|
|||||||
if (ok) {
|
if (ok) {
|
||||||
final nowSaved = favorites.isSaved(drama.id);
|
final nowSaved = favorites.isSaved(drama.id);
|
||||||
if (nowSaved != wasSaved) {
|
if (nowSaved != wasSaved) {
|
||||||
_applyFavoriteDelta(drama, nowSaved: nowSaved);
|
_applyFavoriteDelta(drama.id, nowSaved: nowSaved);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (favorites.lastErrorCode == 200007) {
|
|
||||||
await ensureSignedIn(context);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Text(AppLocalizations.of(context)!.favoriteToggleFailed),
|
content: Text(AppLocalizations.of(context)!.favoriteToggleFailed),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import 'package:flutter/services.dart';
|
|||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../../../core/data/models/comment.dart';
|
import '../../../core/data/models/comment.dart';
|
||||||
|
import '../../../core/data/services/auth_controller.dart';
|
||||||
import '../../../core/data/services/comment_controller.dart';
|
import '../../../core/data/services/comment_controller.dart';
|
||||||
import '../../../core/platform/haptics.dart';
|
import '../../../core/platform/haptics.dart';
|
||||||
import '../../../core/platform/keyboard_inset.dart';
|
import '../../../core/platform/keyboard_inset.dart';
|
||||||
@@ -195,20 +196,23 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
if (result.errorCode == 200007) {
|
|
||||||
await ensureSignedIn(context);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(content: Text(result.errorMessage ?? l10n.commentPostFailed)),
|
SnackBar(content: Text(result.errorMessage ?? l10n.commentPostFailed)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _authenticate() async {
|
||||||
|
await ensureSignedIn(context);
|
||||||
|
if (!mounted || !context.read<AuthController>().isSignedIn) return;
|
||||||
|
_inputFocus.requestFocus();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
final signedIn = context.watch<AuthController>().isSignedIn;
|
||||||
final hasContent = _input.text.trim().isNotEmpty;
|
final hasContent = _input.text.trim().isNotEmpty;
|
||||||
final canPost = hasContent && !widget.controller.submitting;
|
final canPost = signedIn && hasContent && !widget.controller.submitting;
|
||||||
final multiline = _input.text.contains('\n');
|
final multiline = _input.text.contains('\n');
|
||||||
final bottomInset = _isAndroid
|
final bottomInset = _isAndroid
|
||||||
? _pinnedKeyboardInset
|
? _pinnedKeyboardInset
|
||||||
@@ -243,8 +247,8 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
|
|||||||
key: const Key('comment-composer-input'),
|
key: const Key('comment-composer-input'),
|
||||||
controller: _input,
|
controller: _input,
|
||||||
focusNode: _inputFocus,
|
focusNode: _inputFocus,
|
||||||
readOnly: false,
|
readOnly: !signedIn,
|
||||||
canRequestFocus: true,
|
canRequestFocus: signedIn,
|
||||||
minLines: 1,
|
minLines: 1,
|
||||||
maxLines: 4,
|
maxLines: 4,
|
||||||
maxLength: _maxCommentLength,
|
maxLength: _maxCommentLength,
|
||||||
@@ -258,7 +262,9 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
|
|||||||
),
|
),
|
||||||
cursorColor: AppColors.blue,
|
cursorColor: AppColors.blue,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
hintText: l10n.writeComment,
|
hintText: signedIn
|
||||||
|
? l10n.writeComment
|
||||||
|
: l10n.commentLoginHint,
|
||||||
hintStyle: const TextStyle(
|
hintStyle: const TextStyle(
|
||||||
color: AppColors.muted,
|
color: AppColors.muted,
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
@@ -272,7 +278,7 @@ class _CommentComposerSheetState extends State<CommentComposerSheet> {
|
|||||||
enabledBorder: InputBorder.none,
|
enabledBorder: InputBorder.none,
|
||||||
focusedBorder: InputBorder.none,
|
focusedBorder: InputBorder.none,
|
||||||
),
|
),
|
||||||
onTap: null,
|
onTap: signedIn ? null : _authenticate,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
// 评论楼中楼:展开回复、继续加载,没有下一页时给出结束提示。
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import '../../../core/data/models/comment.dart';
|
|
||||||
import '../../../core/data/services/comment_controller.dart';
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
|
||||||
import '../../../l10n/app_localizations.dart';
|
|
||||||
import 'comment_tile.dart';
|
|
||||||
|
|
||||||
const double _replyIndent = 52;
|
|
||||||
|
|
||||||
/// 一条评论及其回复。
|
|
||||||
class CommentThread extends StatelessWidget {
|
|
||||||
const CommentThread({
|
|
||||||
super.key,
|
|
||||||
required this.comment,
|
|
||||||
required this.controller,
|
|
||||||
required this.handlers,
|
|
||||||
});
|
|
||||||
|
|
||||||
final DramaComment comment;
|
|
||||||
final CommentController controller;
|
|
||||||
final CommentInteractionHandlers handlers;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final replies = controller.repliesFor(comment.id);
|
|
||||||
final expanded = controller.repliesExpanded(comment.id);
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
CommentTile(comment: comment, handlers: handlers),
|
|
||||||
if (comment.replyCount > 0 || replies.isNotEmpty) _toggle(context, expanded),
|
|
||||||
if (expanded) _replies(context, replies),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _toggle(BuildContext context, bool expanded) {
|
|
||||||
final l10n = AppLocalizations.of(context)!;
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.only(left: _replyIndent, bottom: 4),
|
|
||||||
child: TextButton(
|
|
||||||
key: Key('comment-replies-${comment.id}'),
|
|
||||||
onPressed: () => _toggleReplies(context),
|
|
||||||
style: TextButton.styleFrom(
|
|
||||||
foregroundColor: AppColors.muted,
|
|
||||||
padding: EdgeInsets.zero,
|
|
||||||
minimumSize: const Size(0, 24),
|
|
||||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Container(width: 16, height: 1, color: AppColors.border),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Text(
|
|
||||||
expanded ? l10n.hideReplies : l10n.viewReplies(comment.replyCount),
|
|
||||||
style: const TextStyle(
|
|
||||||
color: AppColors.muted,
|
|
||||||
fontSize: 12,
|
|
||||||
fontWeight: FontWeight.w400,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Icon(
|
|
||||||
expanded
|
|
||||||
? Icons.keyboard_arrow_up_rounded
|
|
||||||
: Icons.keyboard_arrow_down_rounded,
|
|
||||||
size: 14,
|
|
||||||
color: AppColors.muted,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _replies(BuildContext context, List<DramaComment> replies) {
|
|
||||||
final l10n = AppLocalizations.of(context)!;
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.only(left: _replyIndent),
|
|
||||||
child: Column(
|
|
||||||
children: [
|
|
||||||
if (controller.repliesLoading(comment.id))
|
|
||||||
const Padding(
|
|
||||||
padding: EdgeInsets.symmetric(vertical: 8),
|
|
||||||
child: CircularProgressIndicator(),
|
|
||||||
),
|
|
||||||
for (final reply in replies)
|
|
||||||
CommentTile(comment: reply, handlers: handlers, isReply: true),
|
|
||||||
if (controller.repliesHasMore(comment.id))
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => controller.loadMoreReplies(comment.id),
|
|
||||||
child: Text(l10n.loadMore),
|
|
||||||
)
|
|
||||||
else if (replies.isNotEmpty)
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
|
||||||
child: Text(
|
|
||||||
l10n.noMoreItems,
|
|
||||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _toggleReplies(BuildContext context) async {
|
|
||||||
if (controller.repliesExpanded(comment.id)) {
|
|
||||||
controller.hideReplies(comment.id);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await controller.loadReplies(comment.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,13 +11,14 @@ import '../../../core/data/models/comment.dart';
|
|||||||
import '../../../core/data/models/drama.dart';
|
import '../../../core/data/models/drama.dart';
|
||||||
import '../../../core/data/repositories/comment_repository.dart';
|
import '../../../core/data/repositories/comment_repository.dart';
|
||||||
import '../../../core/data/repositories/interaction_repository.dart';
|
import '../../../core/data/repositories/interaction_repository.dart';
|
||||||
|
import '../../../core/data/services/auth_controller.dart';
|
||||||
import '../../../core/data/services/comment_controller.dart';
|
import '../../../core/data/services/comment_controller.dart';
|
||||||
import '../../../core/formatting/error_text.dart';
|
import '../../../core/formatting/error_text.dart';
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
|
import '../../../core/widgets/auth_gate.dart';
|
||||||
import '../../../core/widgets/empty_state.dart';
|
import '../../../core/widgets/empty_state.dart';
|
||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
import 'comment_composer_sheet.dart';
|
import 'comment_composer_sheet.dart';
|
||||||
import 'comment_thread.dart';
|
|
||||||
import 'comment_tile.dart';
|
import 'comment_tile.dart';
|
||||||
|
|
||||||
const double _composerRadius = 22;
|
const double _composerRadius = 22;
|
||||||
@@ -25,9 +26,10 @@ const double _composerHeight = 44;
|
|||||||
const double _sendButtonSize = 38;
|
const double _sendButtonSize = 38;
|
||||||
const double _sheetRadius = 20;
|
const double _sheetRadius = 20;
|
||||||
const double _headerHeight = 44;
|
const double _headerHeight = 44;
|
||||||
|
const double _replyIndent = 52;
|
||||||
const double _composerTopGap = 8;
|
const double _composerTopGap = 8;
|
||||||
|
|
||||||
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与设备身份发布。
|
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与登录发布。
|
||||||
class DramaCommentsSheet extends StatefulWidget {
|
class DramaCommentsSheet extends StatefulWidget {
|
||||||
const DramaCommentsSheet({super.key, required this.drama, this.episodeId});
|
const DramaCommentsSheet({super.key, required this.drama, this.episodeId});
|
||||||
|
|
||||||
@@ -90,7 +92,8 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openComposer({DramaComment? replyTo}) async {
|
Future<void> _openComposer({DramaComment? replyTo}) async {
|
||||||
if (!mounted) return;
|
await ensureSignedIn(context);
|
||||||
|
if (!mounted || !context.read<AuthController>().isSignedIn) return;
|
||||||
_removeComposerOverlay();
|
_removeComposerOverlay();
|
||||||
final entry = OverlayEntry(
|
final entry = OverlayEntry(
|
||||||
builder: (_) => CommentComposerSheet(
|
builder: (_) => CommentComposerSheet(
|
||||||
@@ -219,6 +222,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
|
|||||||
Widget _content(BuildContext context) {
|
Widget _content(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final count = _serverCount ?? _controller.exactCount;
|
final count = _serverCount ?? _controller.exactCount;
|
||||||
|
final signedIn = context.watch<AuthController>().isSignedIn;
|
||||||
final composerReserve = _composerHeight + _composerTopGap;
|
final composerReserve = _composerHeight + _composerTopGap;
|
||||||
return Column(
|
return Column(
|
||||||
key: const Key('comment-sheet-content'),
|
key: const Key('comment-sheet-content'),
|
||||||
@@ -265,7 +269,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
|
|||||||
Padding(
|
Padding(
|
||||||
key: const Key('comment-composer-area'),
|
key: const Key('comment-composer-area'),
|
||||||
padding: const EdgeInsets.only(top: _composerTopGap),
|
padding: const EdgeInsets.only(top: _composerTopGap),
|
||||||
child: _fakeComposer(l10n),
|
child: _fakeComposer(l10n, signedIn: signedIn),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -311,7 +315,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
|
|||||||
itemCount: _controller.comments.length + 1,
|
itemCount: _controller.comments.length + 1,
|
||||||
itemBuilder: (context, index) {
|
itemBuilder: (context, index) {
|
||||||
if (index == _controller.comments.length) return _footer(l10n);
|
if (index == _controller.comments.length) return _footer(l10n);
|
||||||
return CommentThread(
|
return _CommentThread(
|
||||||
comment: _controller.comments[index],
|
comment: _controller.comments[index],
|
||||||
controller: _controller,
|
controller: _controller,
|
||||||
handlers: CommentInteractionHandlers(onReply: _beginReply),
|
handlers: CommentInteractionHandlers(onReply: _beginReply),
|
||||||
@@ -334,21 +338,10 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
|
|||||||
child: Text(l10n.loadMore),
|
child: Text(l10n.loadMore),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (_controller.comments.isNotEmpty) {
|
|
||||||
return Padding(
|
|
||||||
key: const Key('paged-list-no-more'),
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
|
||||||
child: Text(
|
|
||||||
l10n.noMoreItems,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return const SizedBox(height: 8);
|
return const SizedBox(height: 8);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _fakeComposer(AppLocalizations l10n) {
|
Widget _fakeComposer(AppLocalizations l10n, {required bool signedIn}) {
|
||||||
return GestureDetector(
|
return GestureDetector(
|
||||||
behavior: HitTestBehavior.opaque,
|
behavior: HitTestBehavior.opaque,
|
||||||
onTap: _openComposer,
|
onTap: _openComposer,
|
||||||
@@ -368,7 +361,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
|
|||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.only(left: 16),
|
padding: const EdgeInsets.only(left: 16),
|
||||||
child: Text(
|
child: Text(
|
||||||
l10n.writeComment,
|
signedIn ? l10n.writeComment : l10n.commentLoginHint,
|
||||||
key: const Key('comment-input-placeholder-label'),
|
key: const Key('comment-input-placeholder-label'),
|
||||||
maxLines: 1,
|
maxLines: 1,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -442,3 +435,100 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _CommentThread extends StatelessWidget {
|
||||||
|
const _CommentThread({
|
||||||
|
required this.comment,
|
||||||
|
required this.controller,
|
||||||
|
required this.handlers,
|
||||||
|
});
|
||||||
|
|
||||||
|
final DramaComment comment;
|
||||||
|
final CommentController controller;
|
||||||
|
final CommentInteractionHandlers handlers;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final replies = controller.repliesFor(comment.id);
|
||||||
|
final expanded = controller.repliesExpanded(comment.id);
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
CommentTile(comment: comment, handlers: handlers),
|
||||||
|
if (comment.replyCount > 0 || replies.isNotEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(left: _replyIndent, bottom: 4),
|
||||||
|
child: TextButton(
|
||||||
|
key: Key('comment-replies-${comment.id}'),
|
||||||
|
onPressed: () => _toggleReplies(context),
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
foregroundColor: AppColors.muted,
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
minimumSize: const Size(0, 24),
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Container(width: 16, height: 1, color: AppColors.border),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
expanded
|
||||||
|
? AppLocalizations.of(context)!.hideReplies
|
||||||
|
: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.viewReplies(comment.replyCount),
|
||||||
|
style: const TextStyle(
|
||||||
|
color: AppColors.muted,
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w400,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Icon(
|
||||||
|
expanded
|
||||||
|
? Icons.keyboard_arrow_up_rounded
|
||||||
|
: Icons.keyboard_arrow_down_rounded,
|
||||||
|
size: 14,
|
||||||
|
color: AppColors.muted,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (expanded)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(left: _replyIndent),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
if (controller.repliesLoading(comment.id))
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 8),
|
||||||
|
child: CircularProgressIndicator(),
|
||||||
|
),
|
||||||
|
for (final reply in replies)
|
||||||
|
CommentTile(
|
||||||
|
comment: reply,
|
||||||
|
handlers: handlers,
|
||||||
|
isReply: true,
|
||||||
|
),
|
||||||
|
if (controller.repliesHasMore(comment.id))
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => controller.loadMoreReplies(comment.id),
|
||||||
|
child: Text(AppLocalizations.of(context)!.loadMore),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _toggleReplies(BuildContext context) async {
|
||||||
|
if (controller.repliesExpanded(comment.id)) {
|
||||||
|
controller.hideReplies(comment.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await controller.loadReplies(comment.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ import '../../../core/theme/app_colors.dart';
|
|||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
import 'home_feed_recommend_panel.dart';
|
import 'home_feed_recommend_panel.dart';
|
||||||
import 'loading_progress_track.dart';
|
import 'loading_progress_track.dart';
|
||||||
import 'player_tap_gesture_region.dart';
|
import 'player_double_tap_hearts.dart';
|
||||||
import 'seek_progress_bar.dart';
|
import 'seek_progress_bar.dart';
|
||||||
import 'scrub_preview_card.dart';
|
import 'scrub_preview_card.dart';
|
||||||
|
|
||||||
@@ -69,7 +69,6 @@ class HomeFeedOverlay extends StatefulWidget {
|
|||||||
this.cancelScrubRequest = 0,
|
this.cancelScrubRequest = 0,
|
||||||
this.thumbnailService,
|
this.thumbnailService,
|
||||||
this.spriteAxisService,
|
this.spriteAxisService,
|
||||||
this.suppressBufferLoading = false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final AppLocalizations l10n;
|
final AppLocalizations l10n;
|
||||||
@@ -105,15 +104,25 @@ class HomeFeedOverlay extends StatefulWidget {
|
|||||||
final int cancelScrubRequest;
|
final int cancelScrubRequest;
|
||||||
final PlaybackThumbnailService? thumbnailService;
|
final PlaybackThumbnailService? thumbnailService;
|
||||||
final SpriteThumbnailAxisService? spriteAxisService;
|
final SpriteThumbnailAxisService? spriteAxisService;
|
||||||
final bool suppressBufferLoading;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<HomeFeedOverlay> createState() => _HomeFeedOverlayState();
|
State<HomeFeedOverlay> createState() => _HomeFeedOverlayState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
||||||
|
static const Duration _singleTapDelay = Duration(milliseconds: 400);
|
||||||
|
|
||||||
bool _scrubbing = false;
|
bool _scrubbing = false;
|
||||||
bool _wasVisibleBeforeScrub = true;
|
bool _wasVisibleBeforeScrub = true;
|
||||||
|
Timer? _singleTapTimer;
|
||||||
|
DateTime? _lastDownAt;
|
||||||
|
DateTime? _blockSingleTapUntil;
|
||||||
|
bool _doubleTapDown = false;
|
||||||
|
bool _likedThisPair = false;
|
||||||
|
int _downSerial = 0;
|
||||||
|
int _tapSeq = 0;
|
||||||
|
int _nextHeartBurstId = 0;
|
||||||
|
final List<({int id, Offset position})> _heartBursts = [];
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didUpdateWidget(covariant HomeFeedOverlay oldWidget) {
|
void didUpdateWidget(covariant HomeFeedOverlay oldWidget) {
|
||||||
@@ -123,24 +132,35 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_tapSeq++;
|
||||||
|
_singleTapTimer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
bottom: false,
|
bottom: false,
|
||||||
child: Stack(
|
child: Stack(
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
children: [
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
child: PlayerTapGestureRegion(
|
child: LayoutBuilder(
|
||||||
key: const ValueKey('home-feed-tap-gesture-region'),
|
builder: (context, constraints) => Listener(
|
||||||
gestureKey: const Key('home-feed-gesture'),
|
onPointerUp: (_) => widget.onBoostEnd(),
|
||||||
enabled: !_scrubbing,
|
onPointerCancel: (_) => widget.onBoostEnd(),
|
||||||
doubleTapEnabled: !widget.locked,
|
onPointerDown: _handlePointerDown,
|
||||||
now: widget.now,
|
child: GestureDetector(
|
||||||
onSingleTap: widget.onTogglePlay,
|
key: const Key('home-feed-gesture'),
|
||||||
onDoubleTapLike: widget.onDoubleTapLike,
|
behavior: HitTestBehavior.opaque,
|
||||||
onLongPressStart: _handleLongPressStart,
|
onTapUp: _handleTapUp,
|
||||||
onInteractionEnd: widget.onBoostEnd,
|
onLongPressStart: (details) =>
|
||||||
|
_handleLongPressStart(details, constraints.maxWidth),
|
||||||
|
onLongPressEnd: (_) => widget.onBoostEnd(),
|
||||||
|
onLongPressCancel: widget.onBoostEnd,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Positioned(
|
Positioned(
|
||||||
@@ -197,12 +217,31 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
|||||||
spriteAxisService: widget.spriteAxisService,
|
spriteAxisService: widget.spriteAxisService,
|
||||||
thumbnailsUrl: widget.episode.thumbnailsUrl,
|
thumbnailsUrl: widget.episode.thumbnailsUrl,
|
||||||
episodeId: widget.episode.id,
|
episodeId: widget.episode.id,
|
||||||
suppressBufferLoading: widget.suppressBufferLoading,
|
posterUrl: widget.drama.posterUrl,
|
||||||
onScrubStart: _startScrub,
|
onScrubStart: _startScrub,
|
||||||
onScrubEnd: _endScrub,
|
onScrubEnd: _endScrub,
|
||||||
onSeek: widget.onSeek,
|
onSeek: widget.onSeek,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
if (_heartBursts.isNotEmpty)
|
||||||
|
Positioned.fill(
|
||||||
|
child: IgnorePointer(
|
||||||
|
child: Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
for (final burst in _heartBursts)
|
||||||
|
Positioned(
|
||||||
|
left: burst.position.dx,
|
||||||
|
top: burst.position.dy - 10,
|
||||||
|
child: PlayerDoubleTapHeartBurst(
|
||||||
|
key: ValueKey(burst.id),
|
||||||
|
onCompleted: () => _removeHeartBurst(burst.id),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -224,8 +263,83 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
|||||||
widget.onScrubEnd?.call(wasVisible);
|
widget.onScrubEnd?.call(wasVisible);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DateTime _now() => widget.now?.call() ?? DateTime.now();
|
||||||
|
|
||||||
|
void _handlePointerDown(PointerDownEvent event) {
|
||||||
|
final now = _now();
|
||||||
|
final previous = _lastDownAt;
|
||||||
|
_downSerial++;
|
||||||
|
_lastDownAt = now;
|
||||||
|
final repeated =
|
||||||
|
previous != null && now.difference(previous) <= _singleTapDelay;
|
||||||
|
if (!repeated) {
|
||||||
|
if (_singleTapBlocked(now)) return;
|
||||||
|
_doubleTapDown = false;
|
||||||
|
_likedThisPair = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_doubleTapDown = true;
|
||||||
|
_blockSingleTapUntil = now.add(_singleTapDelay);
|
||||||
|
_cancelPendingSingleTap();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _singleTapBlocked(DateTime now) {
|
||||||
|
final blockedUntil = _blockSingleTapUntil;
|
||||||
|
return blockedUntil != null && now.isBefore(blockedUntil);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _cancelPendingSingleTap() {
|
||||||
|
_tapSeq++;
|
||||||
|
_singleTapTimer?.cancel();
|
||||||
|
_singleTapTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleTapUp(TapUpDetails details) {
|
||||||
|
final now = _now();
|
||||||
|
if (_doubleTapDown || _singleTapBlocked(now)) {
|
||||||
|
_showDoubleTapLike(details.localPosition);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final serial = _downSerial;
|
||||||
|
final tapSeq = ++_tapSeq;
|
||||||
|
_singleTapTimer?.cancel();
|
||||||
|
late final Timer pending;
|
||||||
|
pending = Timer(_singleTapDelay, () {
|
||||||
|
if (!identical(_singleTapTimer, pending)) return;
|
||||||
|
_singleTapTimer = null;
|
||||||
|
if (!mounted || tapSeq != _tapSeq || serial != _downSerial) return;
|
||||||
|
if (_doubleTapDown || _singleTapBlocked(_now())) return;
|
||||||
|
_lastDownAt = null;
|
||||||
|
widget.onTogglePlay();
|
||||||
|
});
|
||||||
|
_singleTapTimer = pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showDoubleTapLike(Offset position) {
|
||||||
|
if (_likedThisPair) return;
|
||||||
|
_likedThisPair = true;
|
||||||
|
_blockSingleTapUntil = _now().add(_singleTapDelay);
|
||||||
|
_cancelPendingSingleTap();
|
||||||
|
_showHearts(position);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _showHearts(Offset position) {
|
||||||
|
final id = _nextHeartBurstId++;
|
||||||
|
setState(() => _heartBursts.add((id: id, position: position)));
|
||||||
|
widget.onDoubleTapLike?.call(position);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _removeHeartBurst(int id) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _heartBursts.removeWhere((burst) => burst.id == id));
|
||||||
|
}
|
||||||
|
|
||||||
void _handleLongPressStart(LongPressStartDetails details, double width) {
|
void _handleLongPressStart(LongPressStartDetails details, double width) {
|
||||||
final third = width / 3;
|
final third = width / 3;
|
||||||
|
_tapSeq++;
|
||||||
|
_cancelPendingSingleTap();
|
||||||
|
_doubleTapDown = false;
|
||||||
|
_lastDownAt = null;
|
||||||
final dx = details.localPosition.dx;
|
final dx = details.localPosition.dx;
|
||||||
if (dx < third || dx > width - third) {
|
if (dx < third || dx > width - third) {
|
||||||
widget.onBoostStart();
|
widget.onBoostStart();
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class _FeedProgressBar extends StatefulWidget {
|
|||||||
this.spriteAxisService,
|
this.spriteAxisService,
|
||||||
this.thumbnailsUrl,
|
this.thumbnailsUrl,
|
||||||
this.episodeId,
|
this.episodeId,
|
||||||
this.suppressBufferLoading = false,
|
this.posterUrl = '',
|
||||||
this.onScrubStart,
|
this.onScrubStart,
|
||||||
this.onScrubEnd,
|
this.onScrubEnd,
|
||||||
this.onSeek,
|
this.onSeek,
|
||||||
@@ -38,7 +38,7 @@ class _FeedProgressBar extends StatefulWidget {
|
|||||||
final SpriteThumbnailAxisSource? spriteAxisService;
|
final SpriteThumbnailAxisSource? spriteAxisService;
|
||||||
final String? thumbnailsUrl;
|
final String? thumbnailsUrl;
|
||||||
final String? episodeId;
|
final String? episodeId;
|
||||||
final bool suppressBufferLoading;
|
final String posterUrl;
|
||||||
final VoidCallback? onScrubStart;
|
final VoidCallback? onScrubStart;
|
||||||
final VoidCallback? onScrubEnd;
|
final VoidCallback? onScrubEnd;
|
||||||
final ValueChanged<Duration>? onSeek;
|
final ValueChanged<Duration>? onSeek;
|
||||||
@@ -54,7 +54,6 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
Timer? _bufferTimer;
|
Timer? _bufferTimer;
|
||||||
bool _buffering = false;
|
bool _buffering = false;
|
||||||
bool _dragging = false;
|
bool _dragging = false;
|
||||||
Duration? _lastPosition;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -70,7 +69,6 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_buffering = false;
|
_buffering = false;
|
||||||
_lastPosition = null;
|
|
||||||
_attachSource();
|
_attachSource();
|
||||||
}
|
}
|
||||||
if (oldWidget.cancelScrubRequest != widget.cancelScrubRequest) {
|
if (oldWidget.cancelScrubRequest != widget.cancelScrubRequest) {
|
||||||
@@ -81,7 +79,6 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_buffering = false;
|
_buffering = false;
|
||||||
_lastPosition = null;
|
|
||||||
if (widget.locked) {
|
if (widget.locked) {
|
||||||
_dragging = false;
|
_dragging = false;
|
||||||
_preview = null;
|
_preview = null;
|
||||||
@@ -89,13 +86,6 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
_syncBufferState(notify: false);
|
_syncBufferState(notify: false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (oldWidget.suppressBufferLoading != widget.suppressBufferLoading) {
|
|
||||||
_bufferTimer?.cancel();
|
|
||||||
_bufferTimer = null;
|
|
||||||
_buffering = false;
|
|
||||||
_lastPosition = null;
|
|
||||||
_syncBufferState(notify: false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -112,11 +102,7 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
final width = constraints.maxWidth;
|
final width = constraints.maxWidth;
|
||||||
final source = widget.controller;
|
final source = widget.controller;
|
||||||
final scrubbing = _dragging;
|
final scrubbing = _dragging;
|
||||||
final loading =
|
final loading = !widget.locked && !scrubbing && _buffering;
|
||||||
!widget.locked &&
|
|
||||||
!widget.suppressBufferLoading &&
|
|
||||||
!scrubbing &&
|
|
||||||
_buffering;
|
|
||||||
final track = widget.locked
|
final track = widget.locked
|
||||||
? _inactiveTrack()
|
? _inactiveTrack()
|
||||||
: source == null
|
: source == null
|
||||||
@@ -180,6 +166,7 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
spriteAxisService: widget.spriteAxisService,
|
spriteAxisService: widget.spriteAxisService,
|
||||||
thumbnailsUrl: widget.thumbnailsUrl,
|
thumbnailsUrl: widget.thumbnailsUrl,
|
||||||
episodeId: widget.episodeId!,
|
episodeId: widget.episodeId!,
|
||||||
|
posterUrl: widget.posterUrl,
|
||||||
position: previewPosition,
|
position: previewPosition,
|
||||||
duration: video!.duration,
|
duration: video!.duration,
|
||||||
),
|
),
|
||||||
@@ -215,24 +202,14 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
|
|
||||||
void _syncBufferState({bool notify = true}) {
|
void _syncBufferState({bool notify = true}) {
|
||||||
final source = widget.controller;
|
final source = widget.controller;
|
||||||
if (widget.locked || widget.suppressBufferLoading || source == null) {
|
if (widget.locked || source == null) {
|
||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_lastPosition = null;
|
|
||||||
_setBuffering(false, notify: notify);
|
_setBuffering(false, notify: notify);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final value = source.value;
|
final value = source.value;
|
||||||
if (!value.isInitialized) {
|
if (!value.isInitialized) {
|
||||||
_bufferTimer?.cancel();
|
|
||||||
_bufferTimer = null;
|
|
||||||
_lastPosition = null;
|
|
||||||
_setBuffering(false, notify: notify);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final previousPosition = _lastPosition;
|
|
||||||
_lastPosition = value.position;
|
|
||||||
if (previousPosition != null && value.position > previousPosition) {
|
|
||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_setBuffering(false, notify: notify);
|
_setBuffering(false, notify: notify);
|
||||||
@@ -244,22 +221,14 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
|||||||
_setBuffering(false, notify: notify);
|
_setBuffering(false, notify: notify);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (previousPosition == null &&
|
|
||||||
value.isPlaying &&
|
|
||||||
value.position > Duration.zero) {
|
|
||||||
_setBuffering(false, notify: notify);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (_buffering || _bufferTimer != null) return;
|
if (_buffering || _bufferTimer != null) return;
|
||||||
final bufferingPosition = value.position;
|
|
||||||
_bufferTimer = Timer(_bufferDebounce, () {
|
_bufferTimer = Timer(_bufferDebounce, () {
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
final current = widget.controller;
|
final current = widget.controller;
|
||||||
if (!mounted ||
|
if (!mounted ||
|
||||||
current != source ||
|
current != source ||
|
||||||
!current!.value.isInitialized ||
|
!current!.value.isInitialized ||
|
||||||
!current.value.isBuffering ||
|
!current.value.isBuffering) {
|
||||||
current.value.position != bufferingPosition) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_setBuffering(true);
|
_setBuffering(true);
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
|
|||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final dramaTitle = localizedDramaTitle(l10n, widget.drama);
|
final dramaTitle = localizedDramaTitle(l10n, widget.drama);
|
||||||
final synopsis = localizedDramaSynopsis(l10n, widget.drama).trim();
|
final synopsis = localizedDramaSynopsis(l10n, widget.drama).trim();
|
||||||
final genres = _genreValues(Localizations.localeOf(context).languageCode);
|
final genres = _genreValues();
|
||||||
return Column(
|
return Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
@@ -285,9 +285,7 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _genreValues(String languageCode) {
|
List<String> _genreValues() {
|
||||||
final localized = widget.drama.localizedTypeLabels(languageCode);
|
|
||||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
|
||||||
final result = <String>[];
|
final result = <String>[];
|
||||||
for (final value in [widget.drama.genre, widget.drama.category]) {
|
for (final value in [widget.drama.genre, widget.drama.category]) {
|
||||||
for (final part in value.split(_tagSplitter)) {
|
for (final part in value.split(_tagSplitter)) {
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
|
|
||||||
const int _heartDurationMs = 1500;
|
const int _heartDurationMs = 680;
|
||||||
const double _heartPopPortion = 0.18;
|
const double _heartPopPortion = 0.18;
|
||||||
const double _heartStartScale = 0.7;
|
const double _heartStartScale = 0.7;
|
||||||
const double _heartHoldPortion = 0.55;
|
const double _heartHoldPortion = 0.45;
|
||||||
|
|
||||||
const List<_HeartParticle> _hearts = [
|
const List<_HeartParticle> _hearts = [
|
||||||
_HeartParticle(
|
_HeartParticle(
|
||||||
@@ -38,136 +35,75 @@ const List<_HeartParticle> _hearts = [
|
|||||||
|
|
||||||
/// 双击点赞时,在点击位置飘出一小簇心。
|
/// 双击点赞时,在点击位置飘出一小簇心。
|
||||||
class PlayerDoubleTapHeartBurst extends StatefulWidget {
|
class PlayerDoubleTapHeartBurst extends StatefulWidget {
|
||||||
const PlayerDoubleTapHeartBurst({
|
const PlayerDoubleTapHeartBurst({super.key, required this.onCompleted});
|
||||||
super.key,
|
|
||||||
required this.burstId,
|
|
||||||
required this.onCompleted,
|
|
||||||
this.origin = Offset.zero,
|
|
||||||
this.now,
|
|
||||||
});
|
|
||||||
|
|
||||||
final int burstId;
|
|
||||||
final VoidCallback onCompleted;
|
final VoidCallback onCompleted;
|
||||||
final Offset origin;
|
|
||||||
final DateTime Function()? now;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<PlayerDoubleTapHeartBurst> createState() =>
|
State<PlayerDoubleTapHeartBurst> createState() =>
|
||||||
_PlayerDoubleTapHeartBurstState();
|
_PlayerDoubleTapHeartBurstState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst> {
|
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
|
||||||
Timer? _timer;
|
with SingleTickerProviderStateMixin {
|
||||||
late final DateTime _startAt;
|
late final AnimationController _controller;
|
||||||
late final int _totalMs;
|
|
||||||
final Stopwatch _lifetime = Stopwatch();
|
|
||||||
int _elapsedMs = 0;
|
|
||||||
int _tickCount = 0;
|
|
||||||
bool _completed = false;
|
bool _completed = false;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_lifetime.start();
|
final total = _hearts
|
||||||
_startAt = _now();
|
|
||||||
_totalMs = _hearts
|
|
||||||
.map((heart) => heart.delay + _heartDurationMs)
|
.map((heart) => heart.delay + _heartDurationMs)
|
||||||
.reduce((left, right) => left > right ? left : right);
|
.reduce((left, right) => left > right ? left : right);
|
||||||
if (kDebugMode) {
|
_controller = AnimationController(
|
||||||
debugPrint(
|
vsync: this,
|
||||||
'[player] phase=heart-burst-start '
|
duration: Duration(milliseconds: total),
|
||||||
'id=${widget.burstId} count=${_hearts.length} '
|
)..addStatusListener(_onStatus);
|
||||||
'configuredMs=$_totalMs at=${widget.origin.dx.toStringAsFixed(1)},'
|
_controller.forward();
|
||||||
'${widget.origin.dy.toStringAsFixed(1)}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_timer = Timer.periodic(
|
|
||||||
const Duration(milliseconds: 16),
|
|
||||||
(_) => _handleTick(),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
DateTime _now() => widget.now?.call() ?? DateTime.now();
|
void _onStatus(AnimationStatus status) {
|
||||||
|
if (status != AnimationStatus.completed || _completed) return;
|
||||||
void _handleTick() {
|
|
||||||
if (!mounted || _completed) return;
|
|
||||||
final rawElapsedMs = _now().difference(_startAt).inMilliseconds;
|
|
||||||
final elapsedMs = rawElapsedMs < 0
|
|
||||||
? 0
|
|
||||||
: rawElapsedMs > _totalMs
|
|
||||||
? _totalMs
|
|
||||||
: rawElapsedMs;
|
|
||||||
_elapsedMs = elapsedMs;
|
|
||||||
_tickCount++;
|
|
||||||
if (kDebugMode && _tickCount % 10 == 0) {
|
|
||||||
debugPrint(
|
|
||||||
'[player] phase=heart-tick id=${widget.burstId} '
|
|
||||||
'elapsedMs=$_elapsedMs',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (_elapsedMs >= _totalMs) {
|
|
||||||
_complete();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState(() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
void _complete() {
|
|
||||||
if (_completed) return;
|
|
||||||
_completed = true;
|
_completed = true;
|
||||||
_timer?.cancel();
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint(
|
|
||||||
'[player] phase=heart-burst-complete '
|
|
||||||
'id=${widget.burstId} '
|
|
||||||
'configuredMs=$_totalMs',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
widget.onCompleted();
|
widget.onCompleted();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
if (kDebugMode) {
|
_controller
|
||||||
final elapsedMs = _completed ? _totalMs : _elapsedMs;
|
..removeStatusListener(_onStatus)
|
||||||
debugPrint(
|
..dispose();
|
||||||
'[player] phase=heart-burst-dispose '
|
|
||||||
'id=${widget.burstId} elapsedMs=$elapsedMs '
|
|
||||||
'completed=${_completed ? 1 : 0}',
|
|
||||||
);
|
|
||||||
if (!_completed) {
|
|
||||||
debugPrintStack(
|
|
||||||
maxFrames: 30,
|
|
||||||
label:
|
|
||||||
'[player] heart-burst-premature-dispose '
|
|
||||||
'id=${widget.burstId} mount=root-overlay',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_lifetime.stop();
|
|
||||||
_timer?.cancel();
|
|
||||||
_timer = null;
|
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return IgnorePointer(
|
return IgnorePointer(
|
||||||
child: Stack(
|
child: SizedBox.shrink(
|
||||||
fit: StackFit.expand,
|
child: AnimatedBuilder(
|
||||||
clipBehavior: Clip.none,
|
animation: _controller,
|
||||||
children: [
|
builder: (context, _) {
|
||||||
for (var index = 0; index < _hearts.length; index++)
|
final elapsed =
|
||||||
_heart(_hearts[index], _elapsedMs.toDouble(), index),
|
_controller.value * _controller.duration!.inMilliseconds;
|
||||||
],
|
return Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
|
children: [
|
||||||
|
for (var index = 0; index < _hearts.length; index++)
|
||||||
|
_heart(_hearts[index], elapsed, index),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _heart(_HeartParticle heart, double elapsed, int index) {
|
Widget _heart(_HeartParticle heart, double elapsed, int index) {
|
||||||
final rawProgress = (elapsed - heart.delay) / _heartDurationMs;
|
final progress = ((elapsed - heart.delay) / _heartDurationMs).clamp(
|
||||||
if (rawProgress < 0) return const SizedBox.shrink();
|
0.0,
|
||||||
final progress = rawProgress.clamp(0.0, 1.0);
|
1.0,
|
||||||
|
);
|
||||||
|
if (progress <= 0) return const SizedBox.shrink();
|
||||||
final move = Curves.easeOutCubic.transform(progress);
|
final move = Curves.easeOutCubic.transform(progress);
|
||||||
final scale = progress < _heartPopPortion
|
final scale = progress < _heartPopPortion
|
||||||
? _heartStartScale +
|
? _heartStartScale +
|
||||||
@@ -177,8 +113,8 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst> {
|
|||||||
? 1.0
|
? 1.0
|
||||||
: 1 - ((progress - _heartHoldPortion) / (1 - _heartHoldPortion));
|
: 1 - ((progress - _heartHoldPortion) / (1 - _heartHoldPortion));
|
||||||
return Positioned(
|
return Positioned(
|
||||||
left: widget.origin.dx + heart.drift * move - heart.size / 2,
|
left: heart.drift * move - heart.size / 2,
|
||||||
top: widget.origin.dy - heart.size / 2 - heart.travel * move,
|
top: -heart.size / 2 - heart.travel * move,
|
||||||
child: Opacity(
|
child: Opacity(
|
||||||
opacity: opacity.clamp(0.0, 1.0),
|
opacity: opacity.clamp(0.0, 1.0),
|
||||||
child: Transform.scale(
|
child: Transform.scale(
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/widgets.dart';
|
|
||||||
|
|
||||||
/// Tracks heart overlays for the lifetime of one player page.
|
|
||||||
class PlayerHeartOverlayController {
|
|
||||||
final Map<int, OverlayEntry> _entries = {};
|
|
||||||
|
|
||||||
void track(int id, OverlayEntry entry) {
|
|
||||||
_entries[id] = entry;
|
|
||||||
}
|
|
||||||
|
|
||||||
void untrack(int id) {
|
|
||||||
_entries.remove(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
void dispose() {
|
|
||||||
for (final entry in _entries.entries.toList()) {
|
|
||||||
if (entry.value.mounted) entry.value.remove();
|
|
||||||
entry.value.dispose();
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint(
|
|
||||||
'[player] phase=heart-burst-entry-removed '
|
|
||||||
'id=${entry.key} reason=page-dispose',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_entries.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class PlayerHeartOverlayScope extends InheritedWidget {
|
|
||||||
const PlayerHeartOverlayScope({
|
|
||||||
super.key,
|
|
||||||
required this.controller,
|
|
||||||
required super.child,
|
|
||||||
});
|
|
||||||
|
|
||||||
final PlayerHeartOverlayController controller;
|
|
||||||
|
|
||||||
static PlayerHeartOverlayController? maybeOf(BuildContext context) {
|
|
||||||
return context
|
|
||||||
.dependOnInheritedWidgetOfExactType<PlayerHeartOverlayScope>()
|
|
||||||
?.controller;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool updateShouldNotify(PlayerHeartOverlayScope oldWidget) {
|
|
||||||
return controller != oldWidget.controller;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
|
||||||
import '../../../core/theme/app_dimens.dart';
|
|
||||||
|
|
||||||
class PlayerLoadingOverlay extends StatelessWidget {
|
|
||||||
const PlayerLoadingOverlay({
|
|
||||||
super.key,
|
|
||||||
required this.opacity,
|
|
||||||
required this.onFadeEnd,
|
|
||||||
});
|
|
||||||
|
|
||||||
final double opacity;
|
|
||||||
final VoidCallback onFadeEnd;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return AnimatedOpacity(
|
|
||||||
opacity: opacity,
|
|
||||||
duration: const Duration(milliseconds: 140),
|
|
||||||
curve: Curves.easeOut,
|
|
||||||
onEnd: onFadeEnd,
|
|
||||||
child: Container(
|
|
||||||
key: const Key('player-loading-surface'),
|
|
||||||
width: AppDimens.refreshIndicatorSize,
|
|
||||||
height: AppDimens.refreshIndicatorSize,
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: AppColors.refreshIndicatorSurface,
|
|
||||||
borderRadius: BorderRadius.circular(AppDimens.refreshIndicatorRadius),
|
|
||||||
),
|
|
||||||
alignment: Alignment.center,
|
|
||||||
child: const SizedBox.square(
|
|
||||||
dimension: AppDimens.refreshSpinnerSize,
|
|
||||||
child: CircularProgressIndicator(
|
|
||||||
key: Key('player-entry-loading'),
|
|
||||||
color: Colors.white,
|
|
||||||
strokeWidth: AppDimens.refreshSpinnerStroke,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import '../../../core/config/app_config.dart';
|
|
||||||
import '../../../core/data/services/sprite_thumbnail_axis.dart';
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
|
||||||
import '../../../core/widgets/remote_image.dart';
|
|
||||||
import 'scrub_preview_card.dart';
|
|
||||||
|
|
||||||
enum PlayerOpeningFallback { handoff, poster, thumbnails, black }
|
|
||||||
|
|
||||||
PlayerOpeningFallback playerOpeningFallback({
|
|
||||||
String? posterUrl,
|
|
||||||
String? thumbnailsUrl,
|
|
||||||
}) {
|
|
||||||
if (posterUrl?.trim().isNotEmpty ?? false) {
|
|
||||||
return PlayerOpeningFallback.poster;
|
|
||||||
}
|
|
||||||
if (thumbnailsUrl?.trim().isNotEmpty ?? false) {
|
|
||||||
return PlayerOpeningFallback.thumbnails;
|
|
||||||
}
|
|
||||||
return PlayerOpeningFallback.black;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 当前集首帧在视频纹理未就绪时占位;空地址交还纯黑底。
|
|
||||||
Widget? playerOpeningFrame(
|
|
||||||
String? thumbnailsUrl, {
|
|
||||||
String? posterUrl,
|
|
||||||
required SpriteThumbnailAxisSource spriteSource,
|
|
||||||
BoxFit fit = BoxFit.cover,
|
|
||||||
}) {
|
|
||||||
final thumbnails = thumbnailsUrl?.trim() ?? '';
|
|
||||||
final poster = posterUrl?.trim() ?? '';
|
|
||||||
if (playerOpeningFallback(posterUrl: poster, thumbnailsUrl: thumbnails) ==
|
|
||||||
PlayerOpeningFallback.black) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return PlayerOpeningFrame(
|
|
||||||
thumbnailsUrl: thumbnails,
|
|
||||||
posterUrl: poster,
|
|
||||||
spriteSource: spriteSource,
|
|
||||||
fit: fit,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 与视频共用全屏父约束和 BoxFit,切换时保持相同可见区域。
|
|
||||||
class PlayerOpeningFrame extends StatefulWidget {
|
|
||||||
const PlayerOpeningFrame({
|
|
||||||
super.key,
|
|
||||||
required this.thumbnailsUrl,
|
|
||||||
required this.spriteSource,
|
|
||||||
this.posterUrl,
|
|
||||||
this.fit = BoxFit.cover,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// 当前视频原始分辨率首帧地址,优先于雪碧图。
|
|
||||||
final String? posterUrl;
|
|
||||||
|
|
||||||
/// 当前视频雪碧图 WebVTT 地址。
|
|
||||||
final String thumbnailsUrl;
|
|
||||||
|
|
||||||
/// 进度条拖动预览共用的雪碧图时间轴与解码缓存。
|
|
||||||
final SpriteThumbnailAxisSource spriteSource;
|
|
||||||
|
|
||||||
/// 必须与同页视频层使用相同适配规则。
|
|
||||||
final BoxFit fit;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<PlayerOpeningFrame> createState() => _PlayerOpeningFrameState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PlayerOpeningFrameState extends State<PlayerOpeningFrame> {
|
|
||||||
bool _posterFailed = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
widget.spriteSource.addListener(_handleSpriteChanged);
|
|
||||||
_prepareSpriteIfNeeded();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(covariant PlayerOpeningFrame oldWidget) {
|
|
||||||
super.didUpdateWidget(oldWidget);
|
|
||||||
if (oldWidget.posterUrl != widget.posterUrl) {
|
|
||||||
_posterFailed = false;
|
|
||||||
}
|
|
||||||
if (oldWidget.spriteSource != widget.spriteSource) {
|
|
||||||
oldWidget.spriteSource.removeListener(_handleSpriteChanged);
|
|
||||||
widget.spriteSource.addListener(_handleSpriteChanged);
|
|
||||||
_prepareSpriteIfNeeded();
|
|
||||||
}
|
|
||||||
if (oldWidget.posterUrl != widget.posterUrl ||
|
|
||||||
oldWidget.thumbnailsUrl != widget.thumbnailsUrl) {
|
|
||||||
_prepareSpriteIfNeeded();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
widget.spriteSource.removeListener(_handleSpriteChanged);
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleSpriteChanged() {
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
bool get _hasPoster =>
|
|
||||||
!_posterFailed && (widget.posterUrl?.trim().isNotEmpty ?? false);
|
|
||||||
|
|
||||||
void _prepareSpriteIfNeeded() {
|
|
||||||
if (_hasPoster || widget.thumbnailsUrl.trim().isEmpty) return;
|
|
||||||
unawaited(
|
|
||||||
widget.spriteSource.prepareAt(widget.thumbnailsUrl, Duration.zero),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _handlePosterError() {
|
|
||||||
if (!_posterFailed) {
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
if (!mounted || _posterFailed) return;
|
|
||||||
setState(() => _posterFailed = true);
|
|
||||||
_prepareSpriteIfNeeded();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return _spriteOrBlack();
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _spriteOrBlack() {
|
|
||||||
final frame = widget.spriteSource.cachedFrameAt(
|
|
||||||
widget.thumbnailsUrl,
|
|
||||||
Duration.zero,
|
|
||||||
);
|
|
||||||
if (frame == null) return const SizedBox.expand();
|
|
||||||
return SpriteCropPreview(
|
|
||||||
key: const Key('player-opening-sprite'),
|
|
||||||
image: frame.image,
|
|
||||||
sourceRect: frame.sourceRect,
|
|
||||||
fit: widget.fit,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) => Stack(
|
|
||||||
fit: StackFit.expand,
|
|
||||||
children: [
|
|
||||||
const ColoredBox(color: AppColors.mediaBlack),
|
|
||||||
if (_hasPoster)
|
|
||||||
LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
|
|
||||||
return Image.network(
|
|
||||||
AppConfig.mediaUrl(widget.posterUrl!.trim()),
|
|
||||||
key: const Key('player-opening-poster'),
|
|
||||||
fit: widget.fit,
|
|
||||||
cacheWidth: resolveImageDecodePixels(
|
|
||||||
constraints.maxWidth,
|
|
||||||
pixelRatio,
|
|
||||||
),
|
|
||||||
cacheHeight: resolveImageDecodePixels(
|
|
||||||
constraints.maxHeight,
|
|
||||||
pixelRatio,
|
|
||||||
),
|
|
||||||
gaplessPlayback: true,
|
|
||||||
errorBuilder: (_, _, _) => _handlePosterError(),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
)
|
|
||||||
else
|
|
||||||
_spriteOrBlack(),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,6 @@ import '../../../l10n/app_localizations.dart';
|
|||||||
import 'player_center_toggle.dart';
|
import 'player_center_toggle.dart';
|
||||||
import 'interaction_rail.dart';
|
import 'interaction_rail.dart';
|
||||||
import 'player_overlay_models.dart';
|
import 'player_overlay_models.dart';
|
||||||
import 'player_tap_gesture_region.dart';
|
|
||||||
import 'seek_progress_bar.dart';
|
import 'seek_progress_bar.dart';
|
||||||
|
|
||||||
part 'player_overlay_parts.dart';
|
part 'player_overlay_parts.dart';
|
||||||
@@ -37,7 +36,6 @@ class PlayerPlaybackOverlay extends StatelessWidget {
|
|||||||
required this.actions,
|
required this.actions,
|
||||||
required this.controlsVisible,
|
required this.controlsVisible,
|
||||||
required this.scrubbing,
|
required this.scrubbing,
|
||||||
this.suppressProgressLoading = false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/// 展示数据。
|
/// 展示数据。
|
||||||
@@ -51,24 +49,23 @@ class PlayerPlaybackOverlay extends StatelessWidget {
|
|||||||
|
|
||||||
/// 正在拖动进度条。拖动期间清屏,只留进度条。
|
/// 正在拖动进度条。拖动期间清屏,只留进度条。
|
||||||
final bool scrubbing;
|
final bool scrubbing;
|
||||||
final bool suppressProgressLoading;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
child: Stack(
|
child: Stack(
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
children: [
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
child: PlayerTapGestureRegion(
|
child: LayoutBuilder(
|
||||||
key: const ValueKey('player-tap-gesture-region'),
|
builder: (context, constraints) => GestureDetector(
|
||||||
gestureKey: const Key('player-video-tap'),
|
key: const Key('player-video-tap'),
|
||||||
enabled: !scrubbing,
|
behavior: HitTestBehavior.opaque,
|
||||||
doubleTapEnabled: !data.locked,
|
onTap: actions.onTogglePlay,
|
||||||
onSingleTap: actions.onTogglePlay,
|
onLongPressStart: (details) =>
|
||||||
onDoubleTapLike: actions.onDoubleTapLike,
|
_handleLongPressStart(details, constraints.maxWidth),
|
||||||
onLongPressStart: _handleLongPressStart,
|
onLongPressEnd: (_) => actions.onBoostEnd(),
|
||||||
onInteractionEnd: actions.onBoostEnd,
|
onLongPressCancel: actions.onBoostEnd,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
_top(context),
|
_top(context),
|
||||||
@@ -306,9 +303,8 @@ class PlayerPlaybackOverlay extends StatelessWidget {
|
|||||||
spriteAxisService: data.spriteAxisService,
|
spriteAxisService: data.spriteAxisService,
|
||||||
thumbnailsUrl: data.episode.thumbnailsUrl,
|
thumbnailsUrl: data.episode.thumbnailsUrl,
|
||||||
episodeId: data.episode.id,
|
episodeId: data.episode.id,
|
||||||
|
posterUrl: data.drama.posterUrl,
|
||||||
inactiveTrackColor: AppColors.inactiveTrack,
|
inactiveTrackColor: AppColors.inactiveTrack,
|
||||||
fallbackDuration: Duration(seconds: data.episode.durationSec),
|
|
||||||
suppressBufferLoading: suppressProgressLoading,
|
|
||||||
onScrubStart: actions.onScrubStart,
|
onScrubStart: actions.onScrubStart,
|
||||||
onScrubEnd: actions.onScrubEnd,
|
onScrubEnd: actions.onScrubEnd,
|
||||||
onSeek: actions.onSeek,
|
onSeek: actions.onSeek,
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
import 'dart:ui';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:video_player/video_player.dart';
|
import 'package:video_player/video_player.dart';
|
||||||
|
|
||||||
@@ -89,7 +87,6 @@ class PlayerOverlayActions {
|
|||||||
const PlayerOverlayActions({
|
const PlayerOverlayActions({
|
||||||
required this.onBack,
|
required this.onBack,
|
||||||
required this.onTogglePlay,
|
required this.onTogglePlay,
|
||||||
this.onDoubleTapLike,
|
|
||||||
required this.onClear,
|
required this.onClear,
|
||||||
required this.onExitClear,
|
required this.onExitClear,
|
||||||
required this.onDetail,
|
required this.onDetail,
|
||||||
@@ -114,9 +111,6 @@ class PlayerOverlayActions {
|
|||||||
/// 切换播放状态。
|
/// 切换播放状态。
|
||||||
final VoidCallback onTogglePlay;
|
final VoidCallback onTogglePlay;
|
||||||
|
|
||||||
/// 双击画面点赞;位置用于飘心。
|
|
||||||
final ValueChanged<Offset>? onDoubleTapLike;
|
|
||||||
|
|
||||||
/// 进入清屏。
|
/// 进入清屏。
|
||||||
final VoidCallback onClear;
|
final VoidCallback onClear;
|
||||||
|
|
||||||
|
|||||||
@@ -1,214 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:video_player/video_player.dart';
|
|
||||||
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
|
||||||
import 'player_opening_frame.dart';
|
|
||||||
import 'player_video_surface.dart';
|
|
||||||
|
|
||||||
enum PlayerRenderSlotRole { previous, current, next }
|
|
||||||
|
|
||||||
class PlayerRenderSlotData {
|
|
||||||
const PlayerRenderSlotData({
|
|
||||||
required this.role,
|
|
||||||
this.index,
|
|
||||||
this.pagePosition,
|
|
||||||
this.controller,
|
|
||||||
this.videoUrl = '',
|
|
||||||
this.theater = false,
|
|
||||||
this.placeholder,
|
|
||||||
this.warmFrameAvailable = false,
|
|
||||||
this.thumbnailReady = false,
|
|
||||||
this.posterReady = false,
|
|
||||||
this.fallback = PlayerOpeningFallback.black,
|
|
||||||
this.warmSlotReused = false,
|
|
||||||
this.waitForPlaybackFrame = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
final PlayerRenderSlotRole role;
|
|
||||||
final int? index;
|
|
||||||
final double? pagePosition;
|
|
||||||
final VideoPlayerController? controller;
|
|
||||||
final String videoUrl;
|
|
||||||
final bool theater;
|
|
||||||
final Widget? placeholder;
|
|
||||||
final bool warmFrameAvailable;
|
|
||||||
final bool thumbnailReady;
|
|
||||||
final bool posterReady;
|
|
||||||
final PlayerOpeningFallback fallback;
|
|
||||||
final bool warmSlotReused;
|
|
||||||
final bool waitForPlaybackFrame;
|
|
||||||
|
|
||||||
factory PlayerRenderSlotData.empty(PlayerRenderSlotRole role) {
|
|
||||||
return PlayerRenderSlotData(role: role);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 播放画面不随 PageView 生命周期销毁,三个固定槽位只更新控制器和位置。
|
|
||||||
class PlayerRenderStack extends StatefulWidget {
|
|
||||||
const PlayerRenderStack({
|
|
||||||
super.key,
|
|
||||||
required this.pageController,
|
|
||||||
required this.slots,
|
|
||||||
this.onCurrentVideoVisible,
|
|
||||||
});
|
|
||||||
|
|
||||||
final PageController pageController;
|
|
||||||
final Map<PlayerRenderSlotRole, PlayerRenderSlotData> slots;
|
|
||||||
final ValueChanged<int?>? onCurrentVideoVisible;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<PlayerRenderStack> createState() => _PlayerRenderStackState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PlayerRenderStackState extends State<PlayerRenderStack> {
|
|
||||||
int? _lastCurrentIndex;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_lastCurrentIndex = _currentSlot.index;
|
|
||||||
_log(
|
|
||||||
'init current=${_lastCurrentIndex ?? '-'} '
|
|
||||||
'pageController=${identityHashCode(widget.pageController)}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(covariant PlayerRenderStack oldWidget) {
|
|
||||||
super.didUpdateWidget(oldWidget);
|
|
||||||
final currentIndex = _currentSlot.index;
|
|
||||||
if (_lastCurrentIndex != currentIndex) {
|
|
||||||
_log(
|
|
||||||
'session-index previous=${_lastCurrentIndex ?? '-'} '
|
|
||||||
'current=${currentIndex ?? '-'}',
|
|
||||||
);
|
|
||||||
_lastCurrentIndex = currentIndex;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_log(
|
|
||||||
'dispose current=${_lastCurrentIndex ?? '-'} '
|
|
||||||
'pageController=${identityHashCode(widget.pageController)}',
|
|
||||||
);
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
PlayerRenderSlotData get _currentSlot =>
|
|
||||||
widget.slots[PlayerRenderSlotRole.current] ??
|
|
||||||
PlayerRenderSlotData.empty(PlayerRenderSlotRole.current);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return IgnorePointer(
|
|
||||||
child: AnimatedBuilder(
|
|
||||||
animation: widget.pageController,
|
|
||||||
builder: (context, _) {
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final viewportHeight = constraints.maxHeight.isFinite
|
|
||||||
? constraints.maxHeight
|
|
||||||
: MediaQuery.sizeOf(context).height;
|
|
||||||
final pageOffset = _pageOffset();
|
|
||||||
final currentPage = _currentSlot.pagePosition ?? pageOffset;
|
|
||||||
final slots = [
|
|
||||||
_slotData(PlayerRenderSlotRole.previous),
|
|
||||||
_slotData(PlayerRenderSlotRole.current),
|
|
||||||
_slotData(PlayerRenderSlotRole.next),
|
|
||||||
];
|
|
||||||
return Stack(
|
|
||||||
key: const Key('player-render-stack'),
|
|
||||||
fit: StackFit.expand,
|
|
||||||
clipBehavior: Clip.hardEdge,
|
|
||||||
children: [
|
|
||||||
const ColoredBox(
|
|
||||||
key: Key('player-fallback-background'),
|
|
||||||
color: AppColors.mediaBlack,
|
|
||||||
),
|
|
||||||
for (final slot in slots)
|
|
||||||
_positionedSurface(
|
|
||||||
slot,
|
|
||||||
pageOffset: pageOffset,
|
|
||||||
viewportHeight: viewportHeight,
|
|
||||||
fallbackPage: _fallbackPage(slot.role, currentPage),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
PlayerRenderSlotData _slotData(PlayerRenderSlotRole role) {
|
|
||||||
return widget.slots[role] ?? PlayerRenderSlotData.empty(role);
|
|
||||||
}
|
|
||||||
|
|
||||||
double _pageOffset() {
|
|
||||||
if (!widget.pageController.hasClients) {
|
|
||||||
return widget.pageController.initialPage.toDouble();
|
|
||||||
}
|
|
||||||
final position = widget.pageController.position;
|
|
||||||
if (!position.hasPixels ||
|
|
||||||
!position.hasViewportDimension ||
|
|
||||||
position.viewportDimension <= 0) {
|
|
||||||
return widget.pageController.initialPage.toDouble();
|
|
||||||
}
|
|
||||||
return position.pixels / position.viewportDimension;
|
|
||||||
}
|
|
||||||
|
|
||||||
double _fallbackPage(PlayerRenderSlotRole role, double currentPage) {
|
|
||||||
return switch (role) {
|
|
||||||
PlayerRenderSlotRole.previous => currentPage - 1,
|
|
||||||
PlayerRenderSlotRole.current => currentPage,
|
|
||||||
PlayerRenderSlotRole.next => currentPage + 1,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _positionedSurface(
|
|
||||||
PlayerRenderSlotData slot, {
|
|
||||||
required double pageOffset,
|
|
||||||
required double viewportHeight,
|
|
||||||
required double fallbackPage,
|
|
||||||
}) {
|
|
||||||
final slotPage = slot.pagePosition ?? fallbackPage;
|
|
||||||
final offset = (slotPage - pageOffset) * viewportHeight;
|
|
||||||
return Positioned.fill(
|
|
||||||
child: Transform.translate(
|
|
||||||
key: Key('player-render-transform-${slot.role.name}'),
|
|
||||||
offset: Offset(0, offset),
|
|
||||||
child: PlayerVideoSurface(
|
|
||||||
key: ValueKey('player-render-slot-${slot.role.name}'),
|
|
||||||
debugSlot: slot.role.name,
|
|
||||||
debugIndex: slot.index,
|
|
||||||
showFallbackBackground: false,
|
|
||||||
controller: slot.controller,
|
|
||||||
videoUrl: slot.videoUrl,
|
|
||||||
theater: slot.theater,
|
|
||||||
placeholder: slot.placeholder,
|
|
||||||
warmFrameAvailable: slot.warmFrameAvailable,
|
|
||||||
thumbnailReady: slot.thumbnailReady,
|
|
||||||
posterReady: slot.posterReady,
|
|
||||||
fallback: slot.fallback,
|
|
||||||
warmSlotReused: slot.warmSlotReused,
|
|
||||||
waitForPlaybackFrame: slot.waitForPlaybackFrame,
|
|
||||||
onVideoVisible: slot.role == PlayerRenderSlotRole.current
|
|
||||||
? () => widget.onCurrentVideoVisible?.call(slot.index)
|
|
||||||
: null,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _log(String message) {
|
|
||||||
if (!kDebugMode) return;
|
|
||||||
debugPrint(
|
|
||||||
'[player-render] ts=${DateTime.now().millisecondsSinceEpoch} $message',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
// Author: fruit.com.cn
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import 'player_double_tap_hearts.dart';
|
|
||||||
import 'player_heart_overlay_scope.dart';
|
|
||||||
|
|
||||||
typedef PlayerLongPressStartCallback =
|
|
||||||
void Function(LongPressStartDetails details, double width);
|
|
||||||
|
|
||||||
/// 播放画面共用的单击/双击仲裁层。
|
|
||||||
class PlayerTapGestureRegion extends StatefulWidget {
|
|
||||||
const PlayerTapGestureRegion({
|
|
||||||
super.key,
|
|
||||||
required this.gestureKey,
|
|
||||||
required this.onSingleTap,
|
|
||||||
required this.onLongPressStart,
|
|
||||||
required this.onInteractionEnd,
|
|
||||||
this.onDoubleTapLike,
|
|
||||||
this.doubleTapEnabled = true,
|
|
||||||
this.enabled = true,
|
|
||||||
this.now,
|
|
||||||
});
|
|
||||||
|
|
||||||
final Key gestureKey;
|
|
||||||
final VoidCallback onSingleTap;
|
|
||||||
final ValueChanged<Offset>? onDoubleTapLike;
|
|
||||||
final PlayerLongPressStartCallback onLongPressStart;
|
|
||||||
final VoidCallback onInteractionEnd;
|
|
||||||
final bool doubleTapEnabled;
|
|
||||||
final bool enabled;
|
|
||||||
final DateTime Function()? now;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<PlayerTapGestureRegion> createState() => _PlayerTapGestureRegionState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PlayerTapGestureRegionState extends State<PlayerTapGestureRegion> {
|
|
||||||
static const Duration _singleTapDelay = Duration(milliseconds: 320);
|
|
||||||
|
|
||||||
Timer? _singleTapTimer;
|
|
||||||
DateTime? _lastDownAt;
|
|
||||||
DateTime? _blockSingleTapUntil;
|
|
||||||
bool _doubleTapDown = false;
|
|
||||||
bool _likedThisPair = false;
|
|
||||||
int _downSerial = 0;
|
|
||||||
int _tapSeq = 0;
|
|
||||||
int _nextHeartBurstId = 0;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_tapSeq++;
|
|
||||||
_singleTapTimer?.cancel();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return IgnorePointer(
|
|
||||||
ignoring: !widget.enabled,
|
|
||||||
child: LayoutBuilder(
|
|
||||||
builder: (context, constraints) => Listener(
|
|
||||||
onPointerUp: (_) => widget.onInteractionEnd(),
|
|
||||||
onPointerCancel: (_) => widget.onInteractionEnd(),
|
|
||||||
onPointerDown: _handlePointerDown,
|
|
||||||
child: Stack(
|
|
||||||
fit: StackFit.expand,
|
|
||||||
clipBehavior: Clip.none,
|
|
||||||
children: [
|
|
||||||
GestureDetector(
|
|
||||||
key: widget.gestureKey,
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onTapUp: _handleTapUp,
|
|
||||||
onLongPressStart: (details) =>
|
|
||||||
_handleLongPressStart(details, constraints.maxWidth),
|
|
||||||
onLongPressEnd: (_) => widget.onInteractionEnd(),
|
|
||||||
onLongPressCancel: widget.onInteractionEnd,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
DateTime _now() => widget.now?.call() ?? DateTime.now();
|
|
||||||
|
|
||||||
void _handlePointerDown(PointerDownEvent event) {
|
|
||||||
final now = _now();
|
|
||||||
final previous = _lastDownAt;
|
|
||||||
_downSerial++;
|
|
||||||
_lastDownAt = now;
|
|
||||||
final repeated =
|
|
||||||
previous != null && now.difference(previous) <= _singleTapDelay;
|
|
||||||
if (!repeated) {
|
|
||||||
if (_singleTapBlocked(now)) return;
|
|
||||||
_doubleTapDown = false;
|
|
||||||
_likedThisPair = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
_doubleTapDown = true;
|
|
||||||
_blockSingleTapUntil = now.add(_singleTapDelay);
|
|
||||||
_cancelPendingSingleTap();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _singleTapBlocked(DateTime now) {
|
|
||||||
final blockedUntil = _blockSingleTapUntil;
|
|
||||||
return blockedUntil != null && now.isBefore(blockedUntil);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _cancelPendingSingleTap() {
|
|
||||||
_tapSeq++;
|
|
||||||
_singleTapTimer?.cancel();
|
|
||||||
_singleTapTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleTapUp(TapUpDetails details) {
|
|
||||||
final now = _now();
|
|
||||||
if (_doubleTapDown || _singleTapBlocked(now)) {
|
|
||||||
_handleDoubleTapLike(details.globalPosition);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final serial = _downSerial;
|
|
||||||
final tapSeq = ++_tapSeq;
|
|
||||||
_singleTapTimer?.cancel();
|
|
||||||
late final Timer pending;
|
|
||||||
pending = Timer(_singleTapDelay, () {
|
|
||||||
if (!identical(_singleTapTimer, pending)) return;
|
|
||||||
_singleTapTimer = null;
|
|
||||||
if (!mounted || tapSeq != _tapSeq || serial != _downSerial) return;
|
|
||||||
if (_doubleTapDown || _singleTapBlocked(_now())) return;
|
|
||||||
_lastDownAt = null;
|
|
||||||
widget.onSingleTap();
|
|
||||||
});
|
|
||||||
_singleTapTimer = pending;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleDoubleTapLike(Offset globalPosition) {
|
|
||||||
_blockSingleTapUntil = _now().add(_singleTapDelay);
|
|
||||||
_cancelPendingSingleTap();
|
|
||||||
if (!widget.doubleTapEnabled || _likedThisPair) return;
|
|
||||||
_likedThisPair = true;
|
|
||||||
_showHeartBurst(globalPosition);
|
|
||||||
widget.onDoubleTapLike?.call(globalPosition);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _showHeartBurst(Offset globalPosition) {
|
|
||||||
final overlay = Overlay.maybeOf(context, rootOverlay: true);
|
|
||||||
if (overlay == null) return;
|
|
||||||
final overlayBox = overlay.context.findRenderObject();
|
|
||||||
final origin = overlayBox is RenderBox
|
|
||||||
? overlayBox.globalToLocal(globalPosition)
|
|
||||||
: globalPosition;
|
|
||||||
final id = _nextHeartBurstId++;
|
|
||||||
final controller = PlayerHeartOverlayScope.maybeOf(context);
|
|
||||||
var removed = false;
|
|
||||||
late final OverlayEntry entry;
|
|
||||||
void removeEntry() {
|
|
||||||
if (removed) return;
|
|
||||||
removed = true;
|
|
||||||
controller?.untrack(id);
|
|
||||||
if (entry.mounted) entry.remove();
|
|
||||||
entry.dispose();
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint('[player] phase=heart-burst-entry-removed id=$id');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entry = OverlayEntry(
|
|
||||||
builder: (context) => Positioned.fill(
|
|
||||||
child: IgnorePointer(
|
|
||||||
child: PlayerDoubleTapHeartBurst(
|
|
||||||
key: ValueKey('heart-overlay-$id'),
|
|
||||||
burstId: id,
|
|
||||||
origin: origin,
|
|
||||||
now: widget.now,
|
|
||||||
onCompleted: removeEntry,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
controller?.track(id, entry);
|
|
||||||
overlay.insert(entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleLongPressStart(LongPressStartDetails details, double width) {
|
|
||||||
_tapSeq++;
|
|
||||||
_cancelPendingSingleTap();
|
|
||||||
_doubleTapDown = false;
|
|
||||||
_lastDownAt = null;
|
|
||||||
widget.onLongPressStart(details, width);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -49,8 +49,7 @@ class PlayerBlockedNotice extends StatelessWidget {
|
|||||||
|
|
||||||
bool get _needsUnlock =>
|
bool get _needsUnlock =>
|
||||||
accessType == PlayTicket.coinRequired ||
|
accessType == PlayTicket.coinRequired ||
|
||||||
accessType == PlayTicket.vipRequired ||
|
accessType == PlayTicket.vipRequired;
|
||||||
(accessType == null && episode.locked);
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
|||||||
@@ -5,180 +5,80 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:video_player/video_player.dart';
|
import 'package:video_player/video_player.dart';
|
||||||
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
import 'player_opening_frame.dart';
|
|
||||||
|
|
||||||
const Duration _crossFadeDuration = Duration(milliseconds: 180);
|
const Duration _videoFadeDuration = Duration(milliseconds: 200);
|
||||||
const double _errorHorizontal = 32;
|
const double _errorHorizontal = 32;
|
||||||
const int _errorMaxLines = 3;
|
const int _errorMaxLines = 3;
|
||||||
|
|
||||||
/// 播放区只维护一个占位和一个视频层,首帧确认后执行一次交叉淡化。
|
/// 黑色底层与视频层共用同一控制器。清晰度切换时用仍在播放的旧画面盖住新纹理的黑帧。
|
||||||
class PlayerVideoSurface extends StatefulWidget {
|
class PlayerVideoSurface extends StatefulWidget {
|
||||||
const PlayerVideoSurface({
|
const PlayerVideoSurface({
|
||||||
super.key,
|
super.key,
|
||||||
required this.controller,
|
required this.controller,
|
||||||
required this.videoUrl,
|
required this.videoUrl,
|
||||||
required this.theater,
|
required this.theater,
|
||||||
this.placeholder,
|
this.handoff,
|
||||||
this.warmFrameAvailable = false,
|
|
||||||
this.thumbnailReady = false,
|
|
||||||
this.posterReady = false,
|
|
||||||
this.fallback = PlayerOpeningFallback.black,
|
|
||||||
this.warmSlotReused = false,
|
|
||||||
this.waitForPlaybackFrame = false,
|
|
||||||
this.debugSlot = 'default',
|
|
||||||
this.debugIndex,
|
|
||||||
this.showFallbackBackground = true,
|
|
||||||
this.onVideoVisible,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final VideoPlayerController? controller;
|
final VideoPlayerController? controller;
|
||||||
|
final VideoPlayerController? handoff;
|
||||||
/// 视频首帧未确认时唯一的占位 widget。
|
|
||||||
final Widget? placeholder;
|
|
||||||
|
|
||||||
/// 相邻集预热槽已可用时直接出视频,不挂载占位。
|
|
||||||
final bool warmFrameAvailable;
|
|
||||||
|
|
||||||
/// 当前集 t=0 雪碧图是否已命中缓存,仅用于调试判定链。
|
|
||||||
final bool thumbnailReady;
|
|
||||||
|
|
||||||
/// 当前集高清 poster 是否已下发,仅用于调试判定链。
|
|
||||||
final bool posterReady;
|
|
||||||
|
|
||||||
/// 首个视频帧确认前实际选择的唯一占位来源。
|
|
||||||
final PlayerOpeningFallback fallback;
|
|
||||||
|
|
||||||
/// 当前集是否为相邻集预热槽晋升而来。
|
|
||||||
final bool warmSlotReused;
|
|
||||||
|
|
||||||
/// 自动播放中的新集等待 position 首次前进后再移交画面。
|
|
||||||
final bool waitForPlaybackFrame;
|
|
||||||
final String debugSlot;
|
|
||||||
final int? debugIndex;
|
|
||||||
final bool showFallbackBackground;
|
|
||||||
final String videoUrl;
|
final String videoUrl;
|
||||||
final bool theater;
|
final bool theater;
|
||||||
final VoidCallback? onVideoVisible;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<PlayerVideoSurface> createState() => _PlayerVideoSurfaceState();
|
State<PlayerVideoSurface> createState() => _PlayerVideoSurfaceState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _PlayerVideoSurfaceState extends State<PlayerVideoSurface>
|
class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
|
||||||
with SingleTickerProviderStateMixin {
|
String? _lastDebugState;
|
||||||
late final AnimationController _crossFade;
|
|
||||||
VideoPlayerController? _attachedController;
|
|
||||||
Widget? _placeholderSnapshot;
|
|
||||||
Size? _videoSize;
|
|
||||||
bool _playbackStarted = false;
|
|
||||||
bool _frameConfirmed = false;
|
|
||||||
bool _confirmationScheduled = false;
|
|
||||||
bool _transitioning = false;
|
|
||||||
bool _videoVisible = false;
|
|
||||||
bool _videoVisibleNotified = false;
|
|
||||||
String? _lastLayerState;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
_crossFade = AnimationController(vsync: this, duration: _crossFadeDuration)
|
|
||||||
..addStatusListener(_handleFadeStatus);
|
|
||||||
_placeholderSnapshot = widget.placeholder;
|
|
||||||
_attachController(widget.controller);
|
|
||||||
final value = widget.controller?.value;
|
|
||||||
_updatePlaybackFlags(value);
|
|
||||||
_videoSize = value != null && value.isInitialized ? value.size : null;
|
|
||||||
_logSlot('init', value);
|
|
||||||
if (_firstFrameConfirmed(value)) {
|
|
||||||
_confirmFirstFrame(initial: true);
|
|
||||||
} else {
|
|
||||||
_logLayer('placeholder', value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didUpdateWidget(covariant PlayerVideoSurface oldWidget) {
|
void didUpdateWidget(covariant PlayerVideoSurface oldWidget) {
|
||||||
super.didUpdateWidget(oldWidget);
|
super.didUpdateWidget(oldWidget);
|
||||||
if (oldWidget.controller != widget.controller) {
|
if (oldWidget.controller != widget.controller) _lastDebugState = null;
|
||||||
_logSlot('controller-change-before', oldWidget.controller?.value);
|
|
||||||
_detachController(oldWidget.controller);
|
|
||||||
_resetForControllerChange();
|
|
||||||
_attachController(widget.controller);
|
|
||||||
final value = widget.controller?.value;
|
|
||||||
_updatePlaybackFlags(value);
|
|
||||||
_videoSize = value != null && value.isInitialized ? value.size : null;
|
|
||||||
_logSlot('controller-change-after', value);
|
|
||||||
if (_firstFrameConfirmed(value)) {
|
|
||||||
_confirmFirstFrame(initial: true);
|
|
||||||
} else {
|
|
||||||
_logLayer('placeholder', value);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!_transitioning &&
|
|
||||||
!_videoVisible &&
|
|
||||||
oldWidget.placeholder != widget.placeholder) {
|
|
||||||
_placeholderSnapshot = widget.placeholder;
|
|
||||||
}
|
|
||||||
if (oldWidget.thumbnailReady != widget.thumbnailReady ||
|
|
||||||
oldWidget.posterReady != widget.posterReady ||
|
|
||||||
oldWidget.fallback != widget.fallback ||
|
|
||||||
oldWidget.warmSlotReused != widget.warmSlotReused ||
|
|
||||||
oldWidget.warmFrameAvailable != widget.warmFrameAvailable) {
|
|
||||||
final value = widget.controller?.value;
|
|
||||||
_updatePlaybackFlags(value);
|
|
||||||
if (!_frameConfirmed && _firstFrameConfirmed(value)) {
|
|
||||||
_confirmFirstFrame();
|
|
||||||
} else {
|
|
||||||
_logLayer('placeholder', value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_logSlot('dispose', widget.controller?.value);
|
|
||||||
_detachController(widget.controller);
|
|
||||||
_crossFade
|
|
||||||
..removeStatusListener(_handleFadeStatus)
|
|
||||||
..dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final controller = widget.controller;
|
final controller = widget.controller;
|
||||||
final value = controller?.value;
|
if (controller == null) return _frame(null);
|
||||||
final videoSize = _videoSize;
|
return ValueListenableBuilder<VideoPlayerValue>(
|
||||||
final showVideo = controller != null && videoSize != null;
|
valueListenable: controller,
|
||||||
final showPlaceholder = !_videoVisible && _placeholderSnapshot != null;
|
builder: (context, value, _) => _frame(value),
|
||||||
final video = showVideo
|
);
|
||||||
? _VideoLayer(
|
}
|
||||||
controller: controller,
|
|
||||||
size: videoSize,
|
Widget _frame(VideoPlayerValue? value) {
|
||||||
theater: widget.theater,
|
final controller = widget.controller;
|
||||||
)
|
final handoff = _liveHandoff(controller);
|
||||||
: null;
|
final reveal = _shouldReveal(value, handoff != null);
|
||||||
|
_logStateChange(value);
|
||||||
return Stack(
|
return Stack(
|
||||||
fit: StackFit.expand,
|
fit: StackFit.expand,
|
||||||
children: [
|
children: [
|
||||||
if (widget.showFallbackBackground)
|
const ColoredBox(
|
||||||
const ColoredBox(
|
key: Key('player-fallback-background'),
|
||||||
key: Key('player-fallback-background'),
|
color: AppColors.mediaBlack,
|
||||||
color: AppColors.mediaBlack,
|
),
|
||||||
),
|
AnimatedOpacity(
|
||||||
if (showPlaceholder)
|
key: const Key('player-video-opacity'),
|
||||||
KeyedSubtree(
|
opacity: reveal ? 1 : 0,
|
||||||
key: const Key('player-single-placeholder'),
|
duration: handoff != null ? Duration.zero : _videoFadeDuration,
|
||||||
child: _placeholderSnapshot!,
|
curve: Curves.easeOut,
|
||||||
),
|
child: reveal && controller != null
|
||||||
if (_videoVisible && video != null)
|
? _VideoLayer(
|
||||||
KeyedSubtree(key: const Key('player-video-layer'), child: video)
|
controller: controller,
|
||||||
else if (_transitioning && video != null)
|
value: value!,
|
||||||
FadeTransition(
|
theater: widget.theater,
|
||||||
key: const Key('player-video-crossfade'),
|
)
|
||||||
opacity: _crossFade,
|
: const SizedBox.expand(),
|
||||||
child: video,
|
),
|
||||||
|
if (handoff != null)
|
||||||
|
_VideoLayer(
|
||||||
|
key: const Key('player-video-handoff'),
|
||||||
|
controller: handoff,
|
||||||
|
value: handoff.value,
|
||||||
|
theater: widget.theater,
|
||||||
),
|
),
|
||||||
if (kDebugMode && value?.hasError == true)
|
if (kDebugMode && value?.hasError == true)
|
||||||
Center(
|
Center(
|
||||||
@@ -198,242 +98,78 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _attachController(VideoPlayerController? controller) {
|
bool _shouldReveal(VideoPlayerValue? value, bool covered) {
|
||||||
_attachedController = controller;
|
if (value == null || value.hasError || !value.isInitialized) return false;
|
||||||
controller?.addListener(_handleControllerChanged);
|
if (value.size.width <= 0) return false;
|
||||||
|
if (covered) return true;
|
||||||
|
return value.position > Duration.zero || value.isPlaying;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _detachController(VideoPlayerController? controller) {
|
/// 只画会话仍持有的旧画面,控制器一旦被换掉就不再引用。
|
||||||
controller?.removeListener(_handleControllerChanged);
|
VideoPlayerController? _liveHandoff(VideoPlayerController? controller) {
|
||||||
if (_attachedController == controller) _attachedController = null;
|
final handoff = widget.handoff;
|
||||||
|
if (handoff == null || identical(handoff, controller)) return null;
|
||||||
|
return handoff;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _handleControllerChanged() {
|
void _logStateChange(VideoPlayerValue? value) {
|
||||||
final value = widget.controller?.value;
|
|
||||||
final nextSize = value != null && value.isInitialized ? value.size : null;
|
|
||||||
final sizeChanged = nextSize != _videoSize;
|
|
||||||
_updatePlaybackFlags(value);
|
|
||||||
_videoSize = nextSize;
|
|
||||||
if (!_frameConfirmed && _firstFrameConfirmed(value)) {
|
|
||||||
_scheduleFirstFrameConfirmation();
|
|
||||||
} else if (sizeChanged && mounted) {
|
|
||||||
setState(() {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _updatePlaybackFlags(VideoPlayerValue? value) {
|
|
||||||
_playbackStarted = _playbackStarted || value?.isPlaying == true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _scheduleFirstFrameConfirmation() {
|
|
||||||
if (_confirmationScheduled || _frameConfirmed) return;
|
|
||||||
_confirmationScheduled = true;
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint(
|
|
||||||
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} '
|
|
||||||
'slot=${widget.debugSlot} index=${widget.debugIndex ?? '-'} '
|
|
||||||
'phase=first-frame-scheduled',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
if (kDebugMode) {
|
|
||||||
debugPrint(
|
|
||||||
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} '
|
|
||||||
'slot=${widget.debugSlot} index=${widget.debugIndex ?? '-'} '
|
|
||||||
'phase=first-frame-callback mounted=$mounted',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_confirmationScheduled = false;
|
|
||||||
if (!mounted || _frameConfirmed) return;
|
|
||||||
if (_firstFrameConfirmed(widget.controller?.value)) {
|
|
||||||
_confirmFirstFrame();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
WidgetsBinding.instance.scheduleFrame();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _firstFrameConfirmed(VideoPlayerValue? value) {
|
|
||||||
if (value == null ||
|
|
||||||
!value.isInitialized ||
|
|
||||||
value.hasError ||
|
|
||||||
value.size.width <= 0 ||
|
|
||||||
value.size.height <= 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (widget.warmFrameAvailable || !widget.waitForPlaybackFrame) return true;
|
|
||||||
if (value.position > Duration.zero || value.isCompleted) return true;
|
|
||||||
return _playbackStarted && !value.isPlaying && !value.isBuffering;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _confirmFirstFrame({bool initial = false}) {
|
|
||||||
if (_frameConfirmed || _videoSize == null) return;
|
|
||||||
_frameConfirmed = true;
|
|
||||||
_logSlot('firstFrameRendered', widget.controller?.value);
|
|
||||||
final canSkipPlaceholder =
|
|
||||||
widget.warmFrameAvailable || _placeholderSnapshot == null;
|
|
||||||
if (canSkipPlaceholder) {
|
|
||||||
if (initial) {
|
|
||||||
_videoVisible = true;
|
|
||||||
_placeholderSnapshot = null;
|
|
||||||
} else {
|
|
||||||
setState(() {
|
|
||||||
_videoVisible = true;
|
|
||||||
_placeholderSnapshot = null;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
_logLayer('video', widget.controller?.value);
|
|
||||||
_notifyVideoVisible();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (initial) {
|
|
||||||
_transitioning = true;
|
|
||||||
_logLayer('fade-start', widget.controller?.value);
|
|
||||||
_crossFade.forward(from: 0);
|
|
||||||
} else {
|
|
||||||
setState(() {
|
|
||||||
_transitioning = true;
|
|
||||||
_placeholderSnapshot = widget.placeholder;
|
|
||||||
});
|
|
||||||
_logLayer('fade-start', widget.controller?.value);
|
|
||||||
_crossFade.forward(from: 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleFadeStatus(AnimationStatus status) {
|
|
||||||
if (status != AnimationStatus.completed || !mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_transitioning = false;
|
|
||||||
_videoVisible = true;
|
|
||||||
_placeholderSnapshot = null;
|
|
||||||
});
|
|
||||||
_logLayer('fade-end', widget.controller?.value);
|
|
||||||
_notifyVideoVisible();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _resetForControllerChange() {
|
|
||||||
_crossFade.reset();
|
|
||||||
_placeholderSnapshot = widget.placeholder;
|
|
||||||
_videoSize = null;
|
|
||||||
_playbackStarted = false;
|
|
||||||
_frameConfirmed = false;
|
|
||||||
_confirmationScheduled = false;
|
|
||||||
_transitioning = false;
|
|
||||||
_videoVisible = false;
|
|
||||||
_videoVisibleNotified = false;
|
|
||||||
_lastLayerState = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _notifyVideoVisible() {
|
|
||||||
if (_videoVisibleNotified) return;
|
|
||||||
_videoVisibleNotified = true;
|
|
||||||
final callback = widget.onVideoVisible;
|
|
||||||
if (callback == null) return;
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
if (mounted) callback();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void _logLayer(String phase, VideoPlayerValue? value) {
|
|
||||||
if (!kDebugMode) return;
|
if (!kDebugMode) return;
|
||||||
final fallback = phase == 'video' || phase == 'fade-end'
|
final status = _debugStatus(value);
|
||||||
? 'video'
|
|
||||||
: _fallbackLabel(widget.fallback);
|
|
||||||
final signature =
|
final signature =
|
||||||
'slot=${widget.debugSlot} '
|
'$status|${value?.isInitialized ?? false}|'
|
||||||
'index=${widget.debugIndex ?? '-'} '
|
'${value?.errorDescription ?? 'none'}';
|
||||||
'phase=$phase warm=${widget.warmFrameAvailable ? 1 : 0} '
|
if (signature == _lastDebugState) return;
|
||||||
'reusedWarm=${widget.warmSlotReused ? 1 : 0} '
|
_lastDebugState = signature;
|
||||||
'frame=${_frameConfirmed ? 1 : 0} '
|
final source = widget.controller?.dataSource ?? widget.videoUrl;
|
||||||
'poster=${widget.posterReady ? 'ready' : 'none'} '
|
|
||||||
'thumbnails=${widget.thumbnailReady ? 'ready' : 'pending'} '
|
|
||||||
'fallback=$fallback '
|
|
||||||
'init=${value?.isInitialized == true ? 1 : 0} '
|
|
||||||
'position=${value?.position.inMilliseconds ?? 0} '
|
|
||||||
'playing=${value?.isPlaying == true ? 1 : 0} '
|
|
||||||
'buffering=${value?.isBuffering == true ? 1 : 0} '
|
|
||||||
'placeholder=${_placeholderLabel()}';
|
|
||||||
if (signature == _lastLayerState) return;
|
|
||||||
_lastLayerState = signature;
|
|
||||||
debugPrint(
|
debugPrint(
|
||||||
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} $signature',
|
'[video] init=${value?.isInitialized ?? false} '
|
||||||
|
'err=${value?.errorDescription ?? 'none'} host=${_host(source)}',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _logSlot(String phase, VideoPlayerValue? value) {
|
String _debugStatus(VideoPlayerValue? value) {
|
||||||
if (!kDebugMode) return;
|
if (value == null) return 'loading';
|
||||||
debugPrint(
|
if (value.hasError) {
|
||||||
'[player-layer] ts=${DateTime.now().millisecondsSinceEpoch} '
|
return 'error: ${value.errorDescription ?? 'unknown'}';
|
||||||
'slot=${widget.debugSlot} index=${widget.debugIndex ?? '-'} '
|
}
|
||||||
'phase=$phase state=${identityHashCode(this)} '
|
if (value.isBuffering) return 'buffering';
|
||||||
'controller=${widget.controller == null ? '-' : identityHashCode(widget.controller)} '
|
if (value.isInitialized) return 'initialized';
|
||||||
'init=${value?.isInitialized == true ? 1 : 0}',
|
return 'loading';
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String _placeholderLabel() {
|
String _host(String source) {
|
||||||
if (_placeholderSnapshot == null) return 'none';
|
final uri = Uri.tryParse(source);
|
||||||
return switch (widget.fallback) {
|
if (uri == null || uri.host.isEmpty) return 'unknown';
|
||||||
PlayerOpeningFallback.handoff => 'handoff',
|
final port = uri.hasPort
|
||||||
PlayerOpeningFallback.poster => 'poster',
|
? uri.port
|
||||||
PlayerOpeningFallback.thumbnails => 'thumbnails',
|
: uri.scheme == 'https'
|
||||||
PlayerOpeningFallback.black => 'none',
|
? 443
|
||||||
};
|
: 80;
|
||||||
}
|
return '${uri.host}:$port';
|
||||||
|
|
||||||
String _fallbackLabel(PlayerOpeningFallback fallback) {
|
|
||||||
if (_placeholderSnapshot == null) return 'black';
|
|
||||||
return switch (fallback) {
|
|
||||||
PlayerOpeningFallback.handoff => 'handoff',
|
|
||||||
PlayerOpeningFallback.poster => 'poster',
|
|
||||||
PlayerOpeningFallback.thumbnails => 'thumbnails-first-frame',
|
|
||||||
PlayerOpeningFallback.black => 'black',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 将旧 controller 作为唯一占位,不额外叠加 handoff 层。
|
|
||||||
class ControllerFramePlaceholder extends StatelessWidget {
|
|
||||||
const ControllerFramePlaceholder({
|
|
||||||
super.key,
|
|
||||||
required this.controller,
|
|
||||||
required this.theater,
|
|
||||||
});
|
|
||||||
|
|
||||||
final VideoPlayerController controller;
|
|
||||||
final bool theater;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final size = controller.value.size;
|
|
||||||
return FittedBox(
|
|
||||||
fit: theater ? BoxFit.contain : BoxFit.cover,
|
|
||||||
child: SizedBox(
|
|
||||||
width: size.width,
|
|
||||||
height: size.height,
|
|
||||||
child: VideoPlayer(controller, key: ValueKey(controller)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _VideoLayer extends StatelessWidget {
|
class _VideoLayer extends StatelessWidget {
|
||||||
const _VideoLayer({
|
const _VideoLayer({
|
||||||
|
super.key,
|
||||||
required this.controller,
|
required this.controller,
|
||||||
required this.size,
|
required this.value,
|
||||||
required this.theater,
|
required this.theater,
|
||||||
});
|
});
|
||||||
|
|
||||||
final VideoPlayerController controller;
|
final VideoPlayerController controller;
|
||||||
final Size size;
|
final VideoPlayerValue value;
|
||||||
final bool theater;
|
final bool theater;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) => FittedBox(
|
Widget build(BuildContext context) {
|
||||||
fit: theater ? BoxFit.contain : BoxFit.cover,
|
return FittedBox(
|
||||||
child: SizedBox(
|
fit: theater ? BoxFit.contain : BoxFit.cover,
|
||||||
width: size.width,
|
child: SizedBox(
|
||||||
height: size.height,
|
width: value.size.width,
|
||||||
child: VideoPlayer(controller, key: ValueKey(controller)),
|
height: value.size.height,
|
||||||
),
|
child: VideoPlayer(controller, key: ValueKey(controller)),
|
||||||
);
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@ import 'package:flutter/material.dart';
|
|||||||
import '../../../core/data/services/playback_thumbnail_service.dart';
|
import '../../../core/data/services/playback_thumbnail_service.dart';
|
||||||
import '../../../core/data/services/sprite_thumbnail_axis.dart';
|
import '../../../core/data/services/sprite_thumbnail_axis.dart';
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
|
import '../../../core/widgets/remote_image.dart';
|
||||||
|
|
||||||
const double scrubPreviewWidth = 96;
|
const double scrubPreviewWidth = 96;
|
||||||
const double scrubPreviewSafeMargin = 12;
|
const double scrubPreviewSafeMargin = 12;
|
||||||
@@ -35,6 +36,7 @@ class ScrubPreviewCard extends StatefulWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
required this.service,
|
required this.service,
|
||||||
required this.episodeId,
|
required this.episodeId,
|
||||||
|
required this.posterUrl,
|
||||||
required this.position,
|
required this.position,
|
||||||
required this.duration,
|
required this.duration,
|
||||||
this.spriteAxisService,
|
this.spriteAxisService,
|
||||||
@@ -45,6 +47,7 @@ class ScrubPreviewCard extends StatefulWidget {
|
|||||||
final SpriteThumbnailAxisSource? spriteAxisService;
|
final SpriteThumbnailAxisSource? spriteAxisService;
|
||||||
final String? thumbnailsUrl;
|
final String? thumbnailsUrl;
|
||||||
final String episodeId;
|
final String episodeId;
|
||||||
|
final String posterUrl;
|
||||||
final Duration position;
|
final Duration position;
|
||||||
final Duration duration;
|
final Duration duration;
|
||||||
|
|
||||||
@@ -204,9 +207,11 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
|
|||||||
child: Stack(
|
child: Stack(
|
||||||
fit: StackFit.expand,
|
fit: StackFit.expand,
|
||||||
children: [
|
children: [
|
||||||
const ColoredBox(
|
RemoteImage(
|
||||||
key: Key('scrub-preview-background'),
|
widget.posterUrl,
|
||||||
color: AppColors.bar,
|
key: const Key('scrub-preview-poster'),
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
fallbackColor: AppColors.bar,
|
||||||
),
|
),
|
||||||
if (stage == ScrubPreviewStage.sprite && spriteFrame != null)
|
if (stage == ScrubPreviewStage.sprite && spriteFrame != null)
|
||||||
SpriteCropPreview(
|
SpriteCropPreview(
|
||||||
@@ -251,33 +256,26 @@ class SpriteCropPreview extends StatelessWidget {
|
|||||||
super.key,
|
super.key,
|
||||||
required this.image,
|
required this.image,
|
||||||
required this.sourceRect,
|
required this.sourceRect,
|
||||||
this.fit = BoxFit.cover,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final ui.Image image;
|
final ui.Image image;
|
||||||
final ui.Rect sourceRect;
|
final ui.Rect sourceRect;
|
||||||
final BoxFit fit;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) => CustomPaint(
|
Widget build(BuildContext context) => CustomPaint(
|
||||||
painter: _SpriteCropPainter(image: image, sourceRect: sourceRect, fit: fit),
|
painter: _SpriteCropPainter(image: image, sourceRect: sourceRect),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
class _SpriteCropPainter extends CustomPainter {
|
class _SpriteCropPainter extends CustomPainter {
|
||||||
const _SpriteCropPainter({
|
const _SpriteCropPainter({required this.image, required this.sourceRect});
|
||||||
required this.image,
|
|
||||||
required this.sourceRect,
|
|
||||||
required this.fit,
|
|
||||||
});
|
|
||||||
|
|
||||||
final ui.Image image;
|
final ui.Image image;
|
||||||
final ui.Rect sourceRect;
|
final ui.Rect sourceRect;
|
||||||
final BoxFit fit;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void paint(Canvas canvas, Size size) {
|
void paint(Canvas canvas, Size size) {
|
||||||
final fitted = applyBoxFit(fit, sourceRect.size, size);
|
final fitted = applyBoxFit(BoxFit.cover, sourceRect.size, size);
|
||||||
final sourceOffset = Alignment.center.inscribe(
|
final sourceOffset = Alignment.center.inscribe(
|
||||||
fitted.source,
|
fitted.source,
|
||||||
Offset.zero & sourceRect.size,
|
Offset.zero & sourceRect.size,
|
||||||
@@ -304,9 +302,7 @@ class _SpriteCropPainter extends CustomPainter {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
bool shouldRepaint(covariant _SpriteCropPainter oldDelegate) =>
|
bool shouldRepaint(covariant _SpriteCropPainter oldDelegate) =>
|
||||||
oldDelegate.image != image ||
|
oldDelegate.image != image || oldDelegate.sourceRect != sourceRect;
|
||||||
oldDelegate.sourceRect != sourceRect ||
|
|
||||||
oldDelegate.fit != fit;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String _format(Duration value) {
|
String _format(Duration value) {
|
||||||
|
|||||||
@@ -41,9 +41,8 @@ class SeekProgressBar extends StatefulWidget {
|
|||||||
this.thumbnailService,
|
this.thumbnailService,
|
||||||
this.spriteAxisService,
|
this.spriteAxisService,
|
||||||
this.episodeId,
|
this.episodeId,
|
||||||
|
this.posterUrl = '',
|
||||||
this.thumbnailsUrl,
|
this.thumbnailsUrl,
|
||||||
this.fallbackDuration = Duration.zero,
|
|
||||||
this.suppressBufferLoading = false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final ValueListenable<VideoPlayerValue>? valueListenable;
|
final ValueListenable<VideoPlayerValue>? valueListenable;
|
||||||
@@ -58,9 +57,8 @@ class SeekProgressBar extends StatefulWidget {
|
|||||||
final PlaybackThumbnailService? thumbnailService;
|
final PlaybackThumbnailService? thumbnailService;
|
||||||
final SpriteThumbnailAxisService? spriteAxisService;
|
final SpriteThumbnailAxisService? spriteAxisService;
|
||||||
final String? episodeId;
|
final String? episodeId;
|
||||||
|
final String posterUrl;
|
||||||
final String? thumbnailsUrl;
|
final String? thumbnailsUrl;
|
||||||
final Duration fallbackDuration;
|
|
||||||
final bool suppressBufferLoading;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<SeekProgressBar> createState() => _SeekProgressBarState();
|
State<SeekProgressBar> createState() => _SeekProgressBarState();
|
||||||
@@ -76,7 +74,6 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
bool _pointerMoved = false;
|
bool _pointerMoved = false;
|
||||||
Offset? _pointerStart;
|
Offset? _pointerStart;
|
||||||
double? _dragStartFraction;
|
double? _dragStartFraction;
|
||||||
Duration? _lastPosition;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -93,22 +90,13 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_buffering = false;
|
_buffering = false;
|
||||||
_lastPosition = null;
|
|
||||||
widget.thumbnailService?.cancelPending();
|
widget.thumbnailService?.cancelPending();
|
||||||
_attachSource();
|
_attachSource();
|
||||||
}
|
}
|
||||||
if (oldWidget.suppressBufferLoading != widget.suppressBufferLoading) {
|
|
||||||
_bufferTimer?.cancel();
|
|
||||||
_bufferTimer = null;
|
|
||||||
_lastPosition = null;
|
|
||||||
_buffering = false;
|
|
||||||
_syncBufferState(notify: false);
|
|
||||||
}
|
|
||||||
if (oldWidget.locked != widget.locked) {
|
if (oldWidget.locked != widget.locked) {
|
||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_buffering = false;
|
_buffering = false;
|
||||||
_lastPosition = null;
|
|
||||||
if (widget.locked) {
|
if (widget.locked) {
|
||||||
widget.thumbnailService?.cancelPending();
|
widget.thumbnailService?.cancelPending();
|
||||||
_previewFraction.value = null;
|
_previewFraction.value = null;
|
||||||
@@ -142,24 +130,14 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
|
|
||||||
void _syncBufferState({bool notify = true}) {
|
void _syncBufferState({bool notify = true}) {
|
||||||
final source = widget.valueListenable;
|
final source = widget.valueListenable;
|
||||||
if (widget.locked || widget.suppressBufferLoading || source == null) {
|
if (widget.locked || source == null) {
|
||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_lastPosition = null;
|
|
||||||
_setBuffering(false, notify: notify);
|
_setBuffering(false, notify: notify);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final value = source.value;
|
final value = source.value;
|
||||||
if (!value.isInitialized) {
|
if (!value.isInitialized) {
|
||||||
_bufferTimer?.cancel();
|
|
||||||
_bufferTimer = null;
|
|
||||||
_lastPosition = null;
|
|
||||||
_setBuffering(false, notify: notify);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final previousPosition = _lastPosition;
|
|
||||||
_lastPosition = value.position;
|
|
||||||
if (previousPosition != null && value.position > previousPosition) {
|
|
||||||
_bufferTimer?.cancel();
|
_bufferTimer?.cancel();
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
_setBuffering(false, notify: notify);
|
_setBuffering(false, notify: notify);
|
||||||
@@ -171,24 +149,14 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
_setBuffering(false, notify: notify);
|
_setBuffering(false, notify: notify);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 首次看到“已播放且有画面”的 buffering 状态时,以 position 为基线,
|
|
||||||
// 不抢先显示 loading;后续 position 停滞超过阈值才视为真实卡顿。
|
|
||||||
if (previousPosition == null &&
|
|
||||||
value.isPlaying &&
|
|
||||||
value.position > Duration.zero) {
|
|
||||||
_setBuffering(false, notify: notify);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (_buffering || _bufferTimer != null) return;
|
if (_buffering || _bufferTimer != null) return;
|
||||||
final bufferingPosition = value.position;
|
|
||||||
_bufferTimer = Timer(_bufferDebounce, () {
|
_bufferTimer = Timer(_bufferDebounce, () {
|
||||||
_bufferTimer = null;
|
_bufferTimer = null;
|
||||||
final current = widget.valueListenable;
|
final current = widget.valueListenable;
|
||||||
if (!mounted ||
|
if (!mounted ||
|
||||||
current != source ||
|
current != source ||
|
||||||
!current!.value.isInitialized ||
|
!current!.value.isInitialized ||
|
||||||
!current.value.isBuffering ||
|
!current.value.isBuffering) {
|
||||||
current.value.position != bufferingPosition) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_setBuffering(true);
|
_setBuffering(true);
|
||||||
@@ -254,16 +222,9 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildTrack(BuildContext context, VideoPlayerValue video) {
|
Widget _buildTrack(BuildContext context, VideoPlayerValue video) {
|
||||||
final duration = video.duration > Duration.zero
|
final total = video.duration.inMilliseconds;
|
||||||
? video.duration
|
|
||||||
: widget.fallbackDuration;
|
|
||||||
final total = duration.inMilliseconds;
|
|
||||||
final scrubbing = _dragging;
|
final scrubbing = _dragging;
|
||||||
final loading =
|
final loading = !widget.locked && !scrubbing && _buffering;
|
||||||
!widget.locked &&
|
|
||||||
!widget.suppressBufferLoading &&
|
|
||||||
!scrubbing &&
|
|
||||||
_buffering;
|
|
||||||
final enabled =
|
final enabled =
|
||||||
!widget.locked &&
|
!widget.locked &&
|
||||||
video.isInitialized &&
|
video.isInitialized &&
|
||||||
@@ -275,12 +236,10 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
final fraction = _previewFraction.value ?? played;
|
final fraction = _previewFraction.value ?? played;
|
||||||
final previewPosition = _previewFraction.value == null
|
final previewPosition = _previewFraction.value == null
|
||||||
? video.position
|
? video.position
|
||||||
: seekPositionForFraction(fraction, duration);
|
: seekPositionForFraction(fraction, video.duration);
|
||||||
final showPreview =
|
final showPreview =
|
||||||
scrubbing &&
|
scrubbing &&
|
||||||
widget.showTimes &&
|
widget.showTimes &&
|
||||||
video.isInitialized &&
|
|
||||||
total > 0 &&
|
|
||||||
widget.thumbnailService != null &&
|
widget.thumbnailService != null &&
|
||||||
(widget.episodeId?.isNotEmpty ?? false);
|
(widget.episodeId?.isNotEmpty ?? false);
|
||||||
final trackHeight = scrubbing ? 6.0 : 2.0;
|
final trackHeight = scrubbing ? 6.0 : 2.0;
|
||||||
@@ -295,7 +254,7 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 2),
|
padding: const EdgeInsets.only(bottom: 2),
|
||||||
child: Text(
|
child: Text(
|
||||||
'${_format(previewPosition)} / ${_format(duration)}',
|
'${_format(previewPosition)} / ${_format(video.duration)}',
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: const TextStyle(
|
style: const TextStyle(
|
||||||
color: AppColors.onPrimary,
|
color: AppColors.onPrimary,
|
||||||
@@ -392,8 +351,9 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
|||||||
spriteAxisService: widget.spriteAxisService,
|
spriteAxisService: widget.spriteAxisService,
|
||||||
thumbnailsUrl: widget.thumbnailsUrl,
|
thumbnailsUrl: widget.thumbnailsUrl,
|
||||||
episodeId: widget.episodeId!,
|
episodeId: widget.episodeId!,
|
||||||
|
posterUrl: widget.posterUrl,
|
||||||
position: previewPosition,
|
position: previewPosition,
|
||||||
duration: duration,
|
duration: video.duration,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -153,8 +153,6 @@ class _RankingPageState extends State<RankingPage> {
|
|||||||
],
|
],
|
||||||
PagedLoadFooter(
|
PagedLoadFooter(
|
||||||
loading: _pager!.loading,
|
loading: _pager!.loading,
|
||||||
hasMore: _pager!.hasMore,
|
|
||||||
hasItems: _pager!.visibleItems.isNotEmpty,
|
|
||||||
loadMoreKey: const Key('ranking-load-more'),
|
loadMoreKey: const Key('ranking-load-more'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -509,13 +507,11 @@ Widget _heat(int count, AppLocalizations l10n) {
|
|||||||
size: 11,
|
size: 11,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Flexible(
|
Text(
|
||||||
child: Text(
|
l10n.heatLabel(formatPlayCount(count)),
|
||||||
l10n.heatLabel(formatPlayCount(count)),
|
maxLines: 1,
|
||||||
maxLines: 1,
|
overflow: TextOverflow.ellipsis,
|
||||||
overflow: TextOverflow.ellipsis,
|
style: const TextStyle(color: AppColors.textTertiary, fontSize: 11),
|
||||||
style: const TextStyle(color: AppColors.textTertiary, fontSize: 11),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,11 +6,8 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../../core/data/models/drama.dart';
|
import '../../core/data/models/drama.dart';
|
||||||
import '../../core/data/remote/catalog_api.dart';
|
|
||||||
import '../../core/data/models/playlist_detail.dart';
|
|
||||||
import '../../core/data/services/category_controller.dart';
|
import '../../core/data/services/category_controller.dart';
|
||||||
import '../../core/data/services/home_feed_controller.dart';
|
import '../../core/data/services/home_feed_controller.dart';
|
||||||
import '../../core/data/services/playlist_controller.dart';
|
|
||||||
import '../../core/theme/app_colors.dart';
|
import '../../core/theme/app_colors.dart';
|
||||||
import '../../core/widgets/empty_state.dart';
|
import '../../core/widgets/empty_state.dart';
|
||||||
import '../../l10n/app_localizations.dart';
|
import '../../l10n/app_localizations.dart';
|
||||||
@@ -26,7 +23,6 @@ class RecommendPage extends StatefulWidget {
|
|||||||
const RecommendPage({
|
const RecommendPage({
|
||||||
super.key,
|
super.key,
|
||||||
required this.feedController,
|
required this.feedController,
|
||||||
this.catalogApi,
|
|
||||||
required this.active,
|
required this.active,
|
||||||
required this.onSearch,
|
required this.onSearch,
|
||||||
this.videoOnly = false,
|
this.videoOnly = false,
|
||||||
@@ -34,7 +30,6 @@ class RecommendPage extends StatefulWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
final HomeFeedController feedController;
|
final HomeFeedController feedController;
|
||||||
final CatalogApi? catalogApi;
|
|
||||||
final bool active;
|
final bool active;
|
||||||
final VoidCallback onSearch;
|
final VoidCallback onSearch;
|
||||||
|
|
||||||
@@ -46,41 +41,11 @@ class RecommendPage extends StatefulWidget {
|
|||||||
State<RecommendPage> createState() => _RecommendPageState();
|
State<RecommendPage> createState() => _RecommendPageState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _RecommendPageState extends State<RecommendPage>
|
class _RecommendPageState extends State<RecommendPage> {
|
||||||
with AutomaticKeepAliveClientMixin<RecommendPage> {
|
|
||||||
RecommendInnerTab _tab = RecommendInnerTab.feed;
|
RecommendInnerTab _tab = RecommendInnerTab.feed;
|
||||||
final PageController _pageController = PageController();
|
final PageController _pageController = PageController();
|
||||||
int _scrubCancelRequest = 0;
|
int _scrubCancelRequest = 0;
|
||||||
|
|
||||||
@override
|
|
||||||
bool get wantKeepAlive => true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
if (widget.active) _scheduleRecommendData();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void didUpdateWidget(RecommendPage oldWidget) {
|
|
||||||
super.didUpdateWidget(oldWidget);
|
|
||||||
if (widget.active && !oldWidget.active) _scheduleRecommendData();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _scheduleRecommendData() {
|
|
||||||
final feed = widget.feedController;
|
|
||||||
if (!feed.loaded && !feed.loadingFirstPage) {
|
|
||||||
unawaited(feed.refreshCurrent());
|
|
||||||
}
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
if (!mounted || !widget.active) return;
|
|
||||||
final playlists = _readPlaylists();
|
|
||||||
if (playlists != null && !playlists.loaded && !playlists.loading) {
|
|
||||||
unawaited(playlists.load());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_pageController.dispose();
|
_pageController.dispose();
|
||||||
@@ -89,7 +54,6 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
super.build(context);
|
|
||||||
final categories = context.read<CategoryController>();
|
final categories = context.read<CategoryController>();
|
||||||
return ColoredBox(
|
return ColoredBox(
|
||||||
key: const Key('recommend-page'),
|
key: const Key('recommend-page'),
|
||||||
@@ -118,7 +82,6 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
child: _withTopNavSpace(
|
child: _withTopNavSpace(
|
||||||
AllDramasFilterGrid(
|
AllDramasFilterGrid(
|
||||||
feedController: widget.feedController,
|
feedController: widget.feedController,
|
||||||
catalogApi: widget.catalogApi,
|
|
||||||
onOpenDrama: _openDrama,
|
onOpenDrama: _openDrama,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -205,22 +168,6 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
PlaylistController? _watchPlaylists(BuildContext context) {
|
|
||||||
try {
|
|
||||||
return context.watch<PlaylistController>();
|
|
||||||
} on ProviderNotFoundException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
PlaylistController? _readPlaylists() {
|
|
||||||
try {
|
|
||||||
return context.read<PlaylistController>();
|
|
||||||
} on ProviderNotFoundException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _recommendPlaylists(CategoryController categories) {
|
Widget _recommendPlaylists(CategoryController categories) {
|
||||||
return DecoratedBox(
|
return DecoratedBox(
|
||||||
key: const Key('recommend-playlist-surface'),
|
key: const Key('recommend-playlist-surface'),
|
||||||
@@ -258,8 +205,6 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
categories: categories,
|
categories: categories,
|
||||||
onOpenDrama: _openDrama,
|
onOpenDrama: _openDrama,
|
||||||
onMore: _handleMore,
|
onMore: _handleMore,
|
||||||
playlists: _watchPlaylists(context),
|
|
||||||
onOpenPlaylist: _openPlaylist,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -307,36 +252,6 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openPlaylist(PlaylistDetail playlist) async {
|
|
||||||
final controller = _readPlaylists();
|
|
||||||
const pageSize = CatalogApi.playlistDramaPageSize;
|
|
||||||
final fresh = controller == null
|
|
||||||
? playlist
|
|
||||||
: await controller.detail(playlist.id, pageSize: pageSize);
|
|
||||||
if (!mounted) return;
|
|
||||||
final shown = fresh.dramas.isEmpty && playlist.dramas.isNotEmpty
|
|
||||||
? playlist
|
|
||||||
: fresh;
|
|
||||||
await Navigator.of(context).push<void>(
|
|
||||||
MaterialPageRoute<void>(
|
|
||||||
builder: (_) => PlaylistDetailPage(
|
|
||||||
title: shown.name,
|
|
||||||
subtitle: shown.description,
|
|
||||||
source: shown,
|
|
||||||
dramas: shown.dramas,
|
|
||||||
dramaCount: shown.dramaCount,
|
|
||||||
loadPage: controller == null
|
|
||||||
? null
|
|
||||||
: (pageIndex) => controller.detail(
|
|
||||||
playlist.id,
|
|
||||||
pageIndex: pageIndex,
|
|
||||||
pageSize: pageSize,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleMore(RecommendSectionKind section) {
|
void _handleMore(RecommendSectionKind section) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final copy = _sectionCopy(l10n, section);
|
final copy = _sectionCopy(l10n, section);
|
||||||
|
|||||||
@@ -1,14 +1,10 @@
|
|||||||
// Author: fruit.com.cn
|
// Author: fruit.com.cn
|
||||||
// 全部短剧:分类、类型、标签多选,列表下拉刷新、上拉加载。
|
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../../core/data/models/content_category.dart';
|
|
||||||
import '../../../core/data/models/drama.dart';
|
import '../../../core/data/models/drama.dart';
|
||||||
import '../../../core/data/remote/catalog_api.dart';
|
|
||||||
import '../../../core/data/services/all_dramas_controller.dart';
|
|
||||||
import '../../../core/data/services/home_feed_controller.dart';
|
import '../../../core/data/services/home_feed_controller.dart';
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
import '../../../core/theme/app_dimens.dart';
|
import '../../../core/theme/app_dimens.dart';
|
||||||
@@ -16,24 +12,21 @@ import '../../../core/widgets/app_pull_to_refresh.dart';
|
|||||||
import '../../../core/widgets/empty_state.dart';
|
import '../../../core/widgets/empty_state.dart';
|
||||||
import '../../../core/widgets/paged_list_footer.dart';
|
import '../../../core/widgets/paged_list_footer.dart';
|
||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
|
import '../../home/widgets/home_drama_classification.dart';
|
||||||
import '../../home/widgets/home_feed_card.dart';
|
import '../../home/widgets/home_feed_card.dart';
|
||||||
|
|
||||||
const double _loadMoreThreshold = 240;
|
const double _loadMoreThreshold = 240;
|
||||||
const int _gridColumns = 3;
|
const List<String> _modernTerms = ['现代', 'modern', 'moderno'];
|
||||||
|
const List<String> _reversalTerms = ['逆袭', 'comeback', 'balas'];
|
||||||
|
|
||||||
/// 推荐页「全部短剧」筛选和三列列表。
|
|
||||||
class AllDramasFilterGrid extends StatefulWidget {
|
class AllDramasFilterGrid extends StatefulWidget {
|
||||||
const AllDramasFilterGrid({
|
const AllDramasFilterGrid({
|
||||||
super.key,
|
super.key,
|
||||||
|
required this.feedController,
|
||||||
required this.onOpenDrama,
|
required this.onOpenDrama,
|
||||||
this.feedController,
|
|
||||||
this.catalogApi,
|
|
||||||
this.controller,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final HomeFeedController? feedController;
|
final HomeFeedController feedController;
|
||||||
final CatalogApi? catalogApi;
|
|
||||||
final AllDramasController? controller;
|
|
||||||
final ValueChanged<Drama> onOpenDrama;
|
final ValueChanged<Drama> onOpenDrama;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -41,143 +34,102 @@ class AllDramasFilterGrid extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
||||||
late final AllDramasController _library;
|
String _region = 'all';
|
||||||
|
String _audio = 'all';
|
||||||
@override
|
String? _genre;
|
||||||
void initState() {
|
bool _newest = false;
|
||||||
super.initState();
|
|
||||||
_library = widget.controller ??
|
|
||||||
AllDramasController(
|
|
||||||
api: widget.catalogApi == null
|
|
||||||
? null
|
|
||||||
: CatalogAllDramasRemote(widget.catalogApi!),
|
|
||||||
);
|
|
||||||
if (_library.usesRemote) {
|
|
||||||
unawaited(_reload());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _reload() async {
|
|
||||||
await _library.refresh();
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _loadMore() async {
|
|
||||||
if (_library.usesRemote) {
|
|
||||||
await _library.loadMore();
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await widget.feedController?.loadMore();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Drama> get _dramas =>
|
|
||||||
_library.usesRemote ? _library.dramas : widget.feedController?.dramas ?? _library.dramas;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
final dramas = _filtered();
|
||||||
return LayoutBuilder(
|
return LayoutBuilder(
|
||||||
builder: (context, constraints) {
|
builder: (context, constraints) {
|
||||||
|
final itemWidth =
|
||||||
|
(constraints.maxWidth -
|
||||||
|
AppDimens.allDramasHorizontal * 2 -
|
||||||
|
AppDimens.allDramasGridGap * 2) /
|
||||||
|
3;
|
||||||
|
final itemExtent =
|
||||||
|
itemWidth / AppDimens.cardCoverAspectRatio +
|
||||||
|
AppDimens.homeCardBodyExtent;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
_filters(l10n),
|
_filters(l10n),
|
||||||
Expanded(child: _dramaList(l10n, _itemExtent(constraints.maxWidth))),
|
Expanded(
|
||||||
|
child: NotificationListener<ScrollNotification>(
|
||||||
|
onNotification: _onScroll,
|
||||||
|
child: AppPullToRefresh(
|
||||||
|
key: const Key('all-dramas-refresh'),
|
||||||
|
onRefresh: () async {
|
||||||
|
await widget.feedController.refreshCurrent();
|
||||||
|
},
|
||||||
|
child: CustomScrollView(
|
||||||
|
key: const Key('all-dramas-scroll'),
|
||||||
|
physics: AppPullToRefresh.physics,
|
||||||
|
slivers: [
|
||||||
|
if (dramas.isEmpty)
|
||||||
|
SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: EmptyState(
|
||||||
|
key: const Key('all-dramas-empty'),
|
||||||
|
icon: Icons.movie_filter_outlined,
|
||||||
|
title: l10n.emptyContent,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: AppDimens.allDramasHorizontal,
|
||||||
|
),
|
||||||
|
sliver: SliverGrid(
|
||||||
|
key: const Key('all-dramas-grid'),
|
||||||
|
gridDelegate:
|
||||||
|
SliverGridDelegateWithFixedCrossAxisCount(
|
||||||
|
crossAxisCount: 3,
|
||||||
|
crossAxisSpacing: AppDimens.allDramasGridGap,
|
||||||
|
mainAxisSpacing:
|
||||||
|
AppDimens.allDramasGridRowGap,
|
||||||
|
mainAxisExtent: itemExtent,
|
||||||
|
),
|
||||||
|
delegate: SliverChildBuilderDelegate(
|
||||||
|
(context, index) => HomeFeedCard(
|
||||||
|
drama: dramas[index],
|
||||||
|
onTap: () => widget.onOpenDrama(dramas[index]),
|
||||||
|
),
|
||||||
|
childCount: dramas.length,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SliverToBoxAdapter(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(
|
||||||
|
bottom: AppDimens.spaceXl,
|
||||||
|
),
|
||||||
|
child: PagedListFooter(
|
||||||
|
loading: widget.feedController.loadingMore,
|
||||||
|
errorMessage:
|
||||||
|
widget.feedController.lastError == null
|
||||||
|
? null
|
||||||
|
: l10n.catalogError,
|
||||||
|
onRetry: widget.feedController.loadMore,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
double _itemExtent(double width) {
|
|
||||||
final itemWidth =
|
|
||||||
(width - AppDimens.allDramasHorizontal * 2 - AppDimens.allDramasGridGap * 2) /
|
|
||||||
_gridColumns;
|
|
||||||
return itemWidth / AppDimens.cardCoverAspectRatio + AppDimens.homeCardBodyExtent;
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _dramaList(AppLocalizations l10n, double itemExtent) {
|
|
||||||
final dramas = _dramas;
|
|
||||||
return NotificationListener<ScrollNotification>(
|
|
||||||
onNotification: _onScroll,
|
|
||||||
child: AppPullToRefresh(
|
|
||||||
key: const Key('all-dramas-refresh'),
|
|
||||||
onRefresh: _refresh,
|
|
||||||
child: CustomScrollView(
|
|
||||||
key: const Key('all-dramas-scroll'),
|
|
||||||
physics: AppPullToRefresh.physics,
|
|
||||||
slivers: [
|
|
||||||
if (dramas.isEmpty) _empty(l10n) else _grid(dramas, itemExtent),
|
|
||||||
_footer(l10n, dramas.isNotEmpty),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _refresh() async {
|
|
||||||
if (_library.usesRemote) {
|
|
||||||
await _reload();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await widget.feedController?.refreshCurrent();
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _empty(AppLocalizations l10n) {
|
|
||||||
return SliverFillRemaining(
|
|
||||||
hasScrollBody: false,
|
|
||||||
child: EmptyState(
|
|
||||||
key: const Key('all-dramas-empty'),
|
|
||||||
icon: Icons.movie_filter_outlined,
|
|
||||||
title: l10n.emptyContent,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _grid(List<Drama> dramas, double itemExtent) {
|
|
||||||
return SliverPadding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: AppDimens.allDramasHorizontal),
|
|
||||||
sliver: SliverGrid(
|
|
||||||
key: const Key('all-dramas-grid'),
|
|
||||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
|
||||||
crossAxisCount: _gridColumns,
|
|
||||||
crossAxisSpacing: AppDimens.allDramasGridGap,
|
|
||||||
mainAxisSpacing: AppDimens.allDramasGridRowGap,
|
|
||||||
mainAxisExtent: itemExtent,
|
|
||||||
),
|
|
||||||
delegate: SliverChildBuilderDelegate(
|
|
||||||
(context, index) => HomeFeedCard(
|
|
||||||
drama: dramas[index],
|
|
||||||
onTap: () => widget.onOpenDrama(dramas[index]),
|
|
||||||
),
|
|
||||||
childCount: dramas.length,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _footer(AppLocalizations l10n, bool hasItems) {
|
|
||||||
return SliverToBoxAdapter(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
|
|
||||||
child: PagedListFooter(
|
|
||||||
loading: _library.usesRemote
|
|
||||||
? _library.loadingMore
|
|
||||||
: widget.feedController?.loadingMore ?? false,
|
|
||||||
hasMore: _library.usesRemote
|
|
||||||
? _library.hasMore
|
|
||||||
: widget.feedController?.hasMore ?? false,
|
|
||||||
hasItems: hasItems,
|
|
||||||
errorMessage: _library.error == null ? null : l10n.catalogError,
|
|
||||||
onRetry: _loadMore,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _filters(AppLocalizations l10n) {
|
Widget _filters(AppLocalizations l10n) {
|
||||||
final languageCode = Localizations.localeOf(context).languageCode;
|
final genres = _availableGenres(l10n);
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(
|
padding: const EdgeInsets.fromLTRB(
|
||||||
AppDimens.allDramasHorizontal,
|
AppDimens.allDramasHorizontal,
|
||||||
@@ -188,75 +140,60 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
|||||||
child: Column(
|
child: Column(
|
||||||
key: const Key('all-dramas-filters'),
|
key: const Key('all-dramas-filters'),
|
||||||
children: [
|
children: [
|
||||||
_optionRow(
|
_selectableRow(
|
||||||
_FilterRow(
|
0,
|
||||||
row: 0,
|
[
|
||||||
group: 'classification',
|
(id: 'all', label: l10n.all),
|
||||||
options: _library.classifications,
|
(id: 'local', label: l10n.localFilter),
|
||||||
selected: _library.selectedClassifications,
|
(id: 'asia', label: l10n.asiaFilter),
|
||||||
onToggle: _library.toggleClassification,
|
(id: 'western', label: l10n.westernFilter),
|
||||||
),
|
],
|
||||||
languageCode,
|
selected: _region,
|
||||||
l10n,
|
onSelected: (value) => setState(() => _region = value),
|
||||||
),
|
),
|
||||||
_optionRow(
|
_selectableRow(
|
||||||
_FilterRow(
|
1,
|
||||||
row: 1,
|
[
|
||||||
group: 'category',
|
(id: 'all', label: l10n.all),
|
||||||
options: _library.categories,
|
(id: 'subtitles', label: l10n.subtitlesOnlyFilter),
|
||||||
selected: _library.selectedCategories,
|
(id: 'dubbed', label: l10n.dubbedFilter),
|
||||||
onToggle: _library.toggleCategory,
|
],
|
||||||
),
|
selected: _audio,
|
||||||
languageCode,
|
onSelected: (value) => setState(() => _audio = value),
|
||||||
l10n,
|
|
||||||
),
|
|
||||||
_optionRow(
|
|
||||||
_FilterRow(
|
|
||||||
row: 2,
|
|
||||||
group: 'tag',
|
|
||||||
options: _library.tags,
|
|
||||||
selected: _library.selectedTags,
|
|
||||||
onToggle: _library.toggleTag,
|
|
||||||
),
|
|
||||||
languageCode,
|
|
||||||
l10n,
|
|
||||||
),
|
),
|
||||||
|
_genreRow(2, genres, l10n),
|
||||||
|
_sortRow(l10n),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _optionRow(_FilterRow spec, String languageCode, AppLocalizations l10n) {
|
Widget _selectableRow(
|
||||||
|
int row,
|
||||||
|
List<({String id, String label})> options, {
|
||||||
|
required String selected,
|
||||||
|
required ValueChanged<String> onSelected,
|
||||||
|
}) {
|
||||||
return _filterRow(
|
return _filterRow(
|
||||||
row: spec.row,
|
row: row,
|
||||||
child: _horizontalChipScroll(
|
child: _horizontalChipScroll(
|
||||||
scrollKey: Key('all-filter-scroll-${spec.row}'),
|
scrollKey: Key('all-filter-scroll-$row'),
|
||||||
chips: [
|
chips: [
|
||||||
_chip(
|
for (var index = 0; index < options.length; index++) ...[
|
||||||
key: Key('all-filter-${spec.group}-all'),
|
|
||||||
label: l10n.all,
|
|
||||||
selected: spec.selected.isEmpty,
|
|
||||||
onTap: () => _select(spec.onToggle, ''),
|
|
||||||
),
|
|
||||||
for (final option in spec.options) ...[
|
|
||||||
const SizedBox(width: AppDimens.filterItemGap),
|
|
||||||
_chip(
|
_chip(
|
||||||
key: Key('all-filter-${spec.group}-${option.id}'),
|
key: Key('all-filter-${options[index].id}'),
|
||||||
label: option.localizedName(languageCode),
|
label: options[index].label,
|
||||||
selected: spec.selected.contains(option.id),
|
selected: selected == options[index].id,
|
||||||
onTap: () => _select(spec.onToggle, option.id),
|
onTap: () => onSelected(options[index].id),
|
||||||
),
|
),
|
||||||
|
if (index < options.length - 1)
|
||||||
|
const SizedBox(width: AppDimens.filterItemGap),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _select(void Function(String id) onToggle, String id) {
|
|
||||||
setState(() => onToggle(id));
|
|
||||||
if (_library.usesRemote) unawaited(_reload());
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _horizontalChipScroll({
|
Widget _horizontalChipScroll({
|
||||||
required Key scrollKey,
|
required Key scrollKey,
|
||||||
required List<Widget> chips,
|
required List<Widget> chips,
|
||||||
@@ -268,17 +205,43 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
|||||||
physics: const BouncingScrollPhysics(),
|
physics: const BouncingScrollPhysics(),
|
||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: BoxConstraints(minWidth: constraints.maxWidth),
|
constraints: BoxConstraints(minWidth: constraints.maxWidth),
|
||||||
child: Row(children: chips),
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
mainAxisAlignment: MainAxisAlignment.start,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.center,
|
||||||
|
children: chips,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _filterRow({required int row, required Widget child}) {
|
Widget _filterRow({
|
||||||
|
required int row,
|
||||||
|
required Widget child,
|
||||||
|
double height = AppDimens.filterChipHeight,
|
||||||
|
}) {
|
||||||
return Padding(
|
return Padding(
|
||||||
key: Key('all-filter-row-$row'),
|
key: Key('all-filter-row-$row'),
|
||||||
padding: EdgeInsets.only(bottom: row < 2 ? AppDimens.filterRowGap : 0),
|
padding: EdgeInsets.only(bottom: row < 3 ? AppDimens.filterRowGap : 0),
|
||||||
child: SizedBox(height: AppDimens.filterChipHeight, child: child),
|
child: SizedBox(height: height, child: child),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _genreRow(
|
||||||
|
int row,
|
||||||
|
List<({String id, String label})> options,
|
||||||
|
AppLocalizations l10n,
|
||||||
|
) {
|
||||||
|
return _selectableRow(
|
||||||
|
row,
|
||||||
|
[
|
||||||
|
(id: 'all', label: l10n.all),
|
||||||
|
for (final genre in options) (id: genre.id, label: genre.label),
|
||||||
|
],
|
||||||
|
selected: _genre ?? 'all',
|
||||||
|
onSelected: (value) =>
|
||||||
|
setState(() => _genre = value == 'all' ? null : value),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,7 +262,9 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
|||||||
),
|
),
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: selected ? AppColors.filterChipSelected : AppColors.transparent,
|
color: selected
|
||||||
|
? AppColors.filterChipSelected
|
||||||
|
: AppColors.transparent,
|
||||||
borderRadius: BorderRadius.circular(AppDimens.filterChipRadius),
|
borderRadius: BorderRadius.circular(AppDimens.filterChipRadius),
|
||||||
),
|
),
|
||||||
child: Text(
|
child: Text(
|
||||||
@@ -317,32 +282,84 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _sortRow(AppLocalizations l10n) {
|
||||||
|
return _filterRow(
|
||||||
|
row: 3,
|
||||||
|
child: _horizontalChipScroll(
|
||||||
|
scrollKey: const Key('all-filter-scroll-3'),
|
||||||
|
chips: [
|
||||||
|
_chip(
|
||||||
|
key: const Key('all-sort-hot'),
|
||||||
|
label: l10n.hot,
|
||||||
|
selected: !_newest,
|
||||||
|
onTap: () => setState(() => _newest = false),
|
||||||
|
),
|
||||||
|
const SizedBox(width: AppDimens.filterItemGap),
|
||||||
|
_chip(
|
||||||
|
key: const Key('all-sort-new'),
|
||||||
|
label: l10n.newest,
|
||||||
|
selected: _newest,
|
||||||
|
onTap: () => setState(() => _newest = true),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<({String id, String label})> _availableGenres(AppLocalizations l10n) {
|
||||||
|
final definitions = [
|
||||||
|
(id: 'reversal', label: l10n.reversalFilter, terms: _reversalTerms),
|
||||||
|
(id: 'uplifting', label: l10n.homeTagUplifting, terms: <String>[]),
|
||||||
|
(id: 'modern', label: l10n.modernFilter, terms: _modernTerms),
|
||||||
|
(id: 'sweet', label: l10n.homeTagSweet, terms: <String>[]),
|
||||||
|
(id: 'angst', label: l10n.homeTagAngst, terms: <String>[]),
|
||||||
|
];
|
||||||
|
return definitions
|
||||||
|
.map((definition) => (id: definition.id, label: definition.label))
|
||||||
|
.toList(growable: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Drama> _filtered() {
|
||||||
|
if (_region != 'all' || _audio != 'all') return const [];
|
||||||
|
final dramas = widget.feedController.dramas
|
||||||
|
.where((drama) {
|
||||||
|
return _genre == null || _matchesGenre(drama, _genre!, const []);
|
||||||
|
})
|
||||||
|
.toList(growable: false);
|
||||||
|
if (_newest) {
|
||||||
|
return [...dramas]..sort((a, b) {
|
||||||
|
final left = publishedAtForDrama(a);
|
||||||
|
final right = publishedAtForDrama(b);
|
||||||
|
if (left == null && right == null) return b.id.compareTo(a.id);
|
||||||
|
if (left == null) return 1;
|
||||||
|
if (right == null) return -1;
|
||||||
|
return right.compareTo(left);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return [...dramas]..sort((a, b) => b.viewCount.compareTo(a.viewCount));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _matchesGenre(Drama drama, String id, List<String> terms) {
|
||||||
|
if (id == 'reversal' ||
|
||||||
|
id == 'uplifting' ||
|
||||||
|
id == 'sweet' ||
|
||||||
|
id == 'angst') {
|
||||||
|
return matchesHomeTag(drama, id == 'reversal' ? 'uplifting' : id);
|
||||||
|
}
|
||||||
|
final text = '${drama.genre} ${drama.category}'.toLowerCase();
|
||||||
|
return terms.any(text.contains);
|
||||||
|
}
|
||||||
|
|
||||||
bool _onScroll(ScrollNotification notification) {
|
bool _onScroll(ScrollNotification notification) {
|
||||||
if (notification.depth != 0) return false;
|
if (notification.depth != 0) return false;
|
||||||
if (notification.metrics.pixels <= 0) return false;
|
final reachedBottom =
|
||||||
final reachedBottom = notification.metrics.extentAfter <= _loadMoreThreshold;
|
notification.metrics.extentAfter <= _loadMoreThreshold;
|
||||||
if (reachedBottom &&
|
if (reachedBottom &&
|
||||||
(notification is ScrollUpdateNotification ||
|
(notification is ScrollUpdateNotification ||
|
||||||
notification is ScrollEndNotification ||
|
notification is ScrollEndNotification ||
|
||||||
notification is OverscrollNotification)) {
|
notification is OverscrollNotification)) {
|
||||||
unawaited(_loadMore());
|
unawaited(widget.feedController.loadMore());
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _FilterRow {
|
|
||||||
const _FilterRow({
|
|
||||||
required this.row,
|
|
||||||
required this.group,
|
|
||||||
required this.options,
|
|
||||||
required this.selected,
|
|
||||||
required this.onToggle,
|
|
||||||
});
|
|
||||||
|
|
||||||
final int row;
|
|
||||||
final String group;
|
|
||||||
final List<ContentCategory> options;
|
|
||||||
final Set<String> selected;
|
|
||||||
final void Function(String id) onToggle;
|
|
||||||
}
|
|
||||||
@@ -3,20 +3,15 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../../core/data/models/drama.dart';
|
import '../../../core/data/models/drama.dart';
|
||||||
import '../../../core/data/models/playlist_detail.dart';
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
import '../../../core/theme/app_dimens.dart';
|
import '../../../core/theme/app_dimens.dart';
|
||||||
import '../../../core/theme/app_theme.dart';
|
import '../../../core/theme/app_theme.dart';
|
||||||
import '../../../core/widgets/app_pull_to_refresh.dart';
|
|
||||||
import '../../../core/widgets/paged_list_footer.dart';
|
|
||||||
import '../../../core/widgets/remote_image.dart';
|
import '../../../core/widgets/remote_image.dart';
|
||||||
import '../../../l10n/app_localizations.dart';
|
|
||||||
import '../../home/widgets/home_feed_card.dart';
|
import '../../home/widgets/home_feed_card.dart';
|
||||||
import '../../player/open_player.dart';
|
import '../../player/open_player.dart';
|
||||||
|
|
||||||
const double _collageHeight = 188;
|
const double _collageHeight = 188;
|
||||||
const int _collageCoverCount = 5;
|
const int _collageCoverCount = 5;
|
||||||
const double _loadMoreThreshold = 200;
|
|
||||||
const double _pageHorizontal = 14;
|
const double _pageHorizontal = 14;
|
||||||
const double _gridGap = 10;
|
const double _gridGap = 10;
|
||||||
const double _sprocketBand = 22;
|
const double _sprocketBand = 22;
|
||||||
@@ -24,88 +19,17 @@ const Color _filmBody = Color(0xFF161311);
|
|||||||
const Color _filmHole = Color(0xFFE6D3BE);
|
const Color _filmHole = Color(0xFFE6D3BE);
|
||||||
|
|
||||||
/// 剧单「更多」:顶部拼图、与剧单一致的标题描述,以及两列卡片。
|
/// 剧单「更多」:顶部拼图、与剧单一致的标题描述,以及两列卡片。
|
||||||
class PlaylistDetailPage extends StatefulWidget {
|
class PlaylistDetailPage extends StatelessWidget {
|
||||||
const PlaylistDetailPage({
|
const PlaylistDetailPage({
|
||||||
super.key,
|
super.key,
|
||||||
required this.title,
|
required this.title,
|
||||||
required this.subtitle,
|
required this.subtitle,
|
||||||
required this.dramas,
|
required this.dramas,
|
||||||
this.dramaCount = 0,
|
|
||||||
this.source,
|
|
||||||
this.loadPage,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final String title;
|
final String title;
|
||||||
final String subtitle;
|
final String subtitle;
|
||||||
final List<Drama> dramas;
|
final List<Drama> dramas;
|
||||||
final PlaylistDetail? source;
|
|
||||||
final int dramaCount;
|
|
||||||
final Future<PlaylistDetail> Function(int pageIndex)? loadPage;
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<PlaylistDetailPage> createState() => _PlaylistDetailPageState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|
||||||
late List<Drama> _dramas = widget.dramas;
|
|
||||||
late int _dramaCount = widget.dramaCount;
|
|
||||||
int _pageIndex = 1;
|
|
||||||
bool _loadingMore = false;
|
|
||||||
bool _failed = false;
|
|
||||||
|
|
||||||
bool get _hasMore =>
|
|
||||||
widget.loadPage != null && _dramas.length < _dramaCount;
|
|
||||||
|
|
||||||
Future<void> _refresh() async {
|
|
||||||
final loadPage = widget.loadPage;
|
|
||||||
if (loadPage == null) return;
|
|
||||||
try {
|
|
||||||
final page = await loadPage(1);
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_dramas = page.dramas;
|
|
||||||
_dramaCount = page.dramaCount;
|
|
||||||
_pageIndex = page.pageIndex == 0 ? 1 : page.pageIndex;
|
|
||||||
_failed = false;
|
|
||||||
});
|
|
||||||
} catch (_) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() => _failed = true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _loadMore() async {
|
|
||||||
final loadPage = widget.loadPage;
|
|
||||||
if (loadPage == null || _loadingMore || !_hasMore) return;
|
|
||||||
setState(() => _loadingMore = true);
|
|
||||||
final next = _pageIndex + 1;
|
|
||||||
try {
|
|
||||||
final page = await loadPage(next);
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() {
|
|
||||||
_dramas = [..._dramas, ...page.dramas];
|
|
||||||
_dramaCount = page.dramaCount;
|
|
||||||
_pageIndex = page.pageIndex == 0 ? next : page.pageIndex;
|
|
||||||
_failed = false;
|
|
||||||
});
|
|
||||||
} catch (_) {
|
|
||||||
if (!mounted) return;
|
|
||||||
setState(() => _failed = true);
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _loadingMore = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _onScroll(ScrollNotification notification) {
|
|
||||||
if (!_hasMore || notification.depth != 0) return false;
|
|
||||||
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
|
|
||||||
if (notification is! ScrollUpdateNotification &&
|
|
||||||
notification is! ScrollEndNotification) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
_loadMore();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -128,16 +52,7 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|||||||
icon: const Icon(Icons.chevron_left_rounded),
|
icon: const Icon(Icons.chevron_left_rounded),
|
||||||
color: AppColors.textPrimary,
|
color: AppColors.textPrimary,
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(child: _body(itemExtent)),
|
||||||
child: NotificationListener<ScrollNotification>(
|
|
||||||
onNotification: _onScroll,
|
|
||||||
child: AppPullToRefresh(
|
|
||||||
key: const Key('playlist-detail-refresh'),
|
|
||||||
onRefresh: _refresh,
|
|
||||||
child: _body(itemExtent),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -148,7 +63,6 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|||||||
Widget _body(double itemExtent) {
|
Widget _body(double itemExtent) {
|
||||||
return CustomScrollView(
|
return CustomScrollView(
|
||||||
key: const Key('playlist-detail-scroll'),
|
key: const Key('playlist-detail-scroll'),
|
||||||
physics: AppPullToRefresh.physics,
|
|
||||||
slivers: [
|
slivers: [
|
||||||
SliverPadding(
|
SliverPadding(
|
||||||
padding: const EdgeInsets.fromLTRB(
|
padding: const EdgeInsets.fromLTRB(
|
||||||
@@ -157,7 +71,7 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|||||||
_pageHorizontal,
|
_pageHorizontal,
|
||||||
12,
|
12,
|
||||||
),
|
),
|
||||||
sliver: SliverToBoxAdapter(child: _PlaylistCollage(dramas: _dramas)),
|
sliver: SliverToBoxAdapter(child: _PlaylistCollage(dramas: dramas)),
|
||||||
),
|
),
|
||||||
SliverPadding(
|
SliverPadding(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: _pageHorizontal),
|
padding: const EdgeInsets.symmetric(horizontal: _pageHorizontal),
|
||||||
@@ -181,22 +95,10 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|||||||
),
|
),
|
||||||
delegate: SliverChildBuilderDelegate(
|
delegate: SliverChildBuilderDelegate(
|
||||||
(context, index) => HomeFeedCard(
|
(context, index) => HomeFeedCard(
|
||||||
drama: _dramas[index],
|
drama: dramas[index],
|
||||||
onTap: () => playDramaFromCatalog(context, _dramas[index]),
|
onTap: () => playDramaFromCatalog(context, dramas[index]),
|
||||||
),
|
),
|
||||||
childCount: _dramas.length,
|
childCount: dramas.length,
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
SliverToBoxAdapter(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.only(bottom: 24),
|
|
||||||
child: PagedListFooter(
|
|
||||||
loading: _loadingMore,
|
|
||||||
hasMore: _hasMore,
|
|
||||||
hasItems: _dramas.isNotEmpty,
|
|
||||||
errorMessage: _failed ? AppLocalizations.of(context)!.catalogError : null,
|
|
||||||
onRetry: _loadingMore ? _loadMore : (_hasMore ? _loadMore : _refresh),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -204,26 +106,12 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
String _title(BuildContext context) {
|
|
||||||
final item = widget.source;
|
|
||||||
if (item == null) return widget.title;
|
|
||||||
return item.localizedName(Localizations.localeOf(context).languageCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _subtitle(BuildContext context) {
|
|
||||||
final item = widget.source;
|
|
||||||
if (item == null) return widget.subtitle;
|
|
||||||
return item.localizedDescription(
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _heading() {
|
Widget _heading() {
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
_title(context),
|
title,
|
||||||
key: const Key('playlist-detail-title'),
|
key: const Key('playlist-detail-title'),
|
||||||
style: const TextStyle(
|
style: const TextStyle(
|
||||||
color: AppColors.textPrimary,
|
color: AppColors.textPrimary,
|
||||||
@@ -233,7 +121,7 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
Text(
|
Text(
|
||||||
_subtitle(context),
|
subtitle,
|
||||||
key: const Key('playlist-detail-subtitle'),
|
key: const Key('playlist-detail-subtitle'),
|
||||||
style: const TextStyle(
|
style: const TextStyle(
|
||||||
color: AppColors.textSecondary,
|
color: AppColors.textSecondary,
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import '../../../core/theme/app_dimens.dart';
|
|||||||
import '../../../core/widgets/cover_play_count.dart';
|
import '../../../core/widgets/cover_play_count.dart';
|
||||||
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
|
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
|
||||||
import '../../../core/widgets/remote_image.dart';
|
import '../../../core/widgets/remote_image.dart';
|
||||||
|
import '../../../l10n/app_localizations.dart';
|
||||||
|
import '../../home/widgets/home_drama_classification.dart';
|
||||||
|
|
||||||
final RegExp _tagSplitter = RegExp(r'[,/、·]');
|
final RegExp _tagSplitter = RegExp(r'[,/、·]');
|
||||||
|
|
||||||
@@ -25,7 +27,7 @@ class RecommendSectionCard extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final tagLabel = drama.localizedTag(Localizations.localeOf(context).languageCode);
|
final l10n = AppLocalizations.of(context)!;
|
||||||
return SizedBox(
|
return SizedBox(
|
||||||
width: AppDimens.recommendCardWidth,
|
width: AppDimens.recommendCardWidth,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
@@ -50,14 +52,14 @@ class RecommendSectionCard extends StatelessWidget {
|
|||||||
showFallbackIcon: true,
|
showFallbackIcon: true,
|
||||||
fallbackColor: AppColors.contentSurface,
|
fallbackColor: AppColors.contentSurface,
|
||||||
),
|
),
|
||||||
if (tagLabel.isNotEmpty)
|
if (isHotDrama(drama))
|
||||||
Positioned(
|
Positioned(
|
||||||
top: 0,
|
top: 0,
|
||||||
right: 0,
|
right: 0,
|
||||||
child: DramaCoverBadgeRibbon(
|
child: DramaCoverBadgeRibbon(
|
||||||
label: tagLabel,
|
label: l10n.homeBadgeHot,
|
||||||
color: drama.tagRibbonColor(AppColors.badgeHot),
|
color: AppColors.badgeHot,
|
||||||
keyPrefix: '$sectionKey-${drama.id}-tag',
|
keyPrefix: '$sectionKey-${drama.id}-hot',
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Positioned(
|
const Positioned(
|
||||||
@@ -80,7 +82,7 @@ class RecommendSectionCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: AppDimens.cardCoverTitleGap),
|
const SizedBox(height: AppDimens.cardCoverTitleGap),
|
||||||
Text(
|
Text(
|
||||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
drama.title,
|
||||||
key: Key('recommend-title-$sectionKey-${drama.id}'),
|
key: Key('recommend-title-$sectionKey-${drama.id}'),
|
||||||
maxLines: 2,
|
maxLines: 2,
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
@@ -92,15 +94,25 @@ class RecommendSectionCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppDimens.cardTitleTagGap),
|
const SizedBox(height: AppDimens.cardTitleTagGap),
|
||||||
_tags(context),
|
_tags(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _tags(BuildContext context) {
|
List<String> _cardTags() {
|
||||||
final tags = _cardTags(context);
|
final seen = <String>{};
|
||||||
|
return [drama.genre, drama.category]
|
||||||
|
.expand((value) => value.split(_tagSplitter))
|
||||||
|
.map((value) => value.trim())
|
||||||
|
.where((value) => value.isNotEmpty && seen.add(value))
|
||||||
|
.take(3)
|
||||||
|
.toList(growable: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _tags() {
|
||||||
|
final tags = _cardTags();
|
||||||
if (tags.isEmpty) return const SizedBox.shrink();
|
if (tags.isEmpty) return const SizedBox.shrink();
|
||||||
return Text(
|
return Text(
|
||||||
tags.join(' | '),
|
tags.join(' | '),
|
||||||
@@ -114,16 +126,4 @@ class RecommendSectionCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> _cardTags(BuildContext context) {
|
|
||||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
|
||||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
|
||||||
final seen = <String>{};
|
|
||||||
return [drama.genre, drama.category]
|
|
||||||
.expand((value) => value.split(_tagSplitter))
|
|
||||||
.map((value) => value.trim())
|
|
||||||
.where((value) => value.isNotEmpty && seen.add(value))
|
|
||||||
.take(3)
|
|
||||||
.toList(growable: false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -4,21 +4,17 @@ import 'package:flutter/material.dart';
|
|||||||
|
|
||||||
import '../../../core/data/models/content_category.dart';
|
import '../../../core/data/models/content_category.dart';
|
||||||
import '../../../core/data/models/drama.dart';
|
import '../../../core/data/models/drama.dart';
|
||||||
import '../../../core/data/models/playlist_detail.dart';
|
|
||||||
import '../../../core/data/services/category_controller.dart';
|
import '../../../core/data/services/category_controller.dart';
|
||||||
import '../../../core/data/services/home_feed_controller.dart';
|
import '../../../core/data/services/home_feed_controller.dart';
|
||||||
import '../../../core/data/services/playlist_controller.dart';
|
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
import '../../../core/theme/app_dimens.dart';
|
import '../../../core/theme/app_dimens.dart';
|
||||||
import '../../../core/widgets/app_pull_to_refresh.dart';
|
import '../../../core/widgets/app_pull_to_refresh.dart';
|
||||||
import '../../../core/widgets/empty_state.dart';
|
|
||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
import '../../home/widgets/home_drama_classification.dart';
|
import '../../home/widgets/home_drama_classification.dart';
|
||||||
import 'recommend_section_card.dart';
|
import 'recommend_section_card.dart';
|
||||||
|
|
||||||
const List<String> _costumeNames = ['古装', 'costume', 'kostum'];
|
const List<String> _costumeNames = ['古装', 'costume', 'kostum'];
|
||||||
const int _sectionPreviewCount = 10;
|
const int _sectionPreviewCount = 10;
|
||||||
const double _loadMoreThreshold = 200;
|
|
||||||
|
|
||||||
enum RecommendSectionKind { hits, newReleases, costume }
|
enum RecommendSectionKind { hits, newReleases, costume }
|
||||||
|
|
||||||
@@ -29,51 +25,17 @@ class RecommendSectionsView extends StatelessWidget {
|
|||||||
required this.categories,
|
required this.categories,
|
||||||
required this.onOpenDrama,
|
required this.onOpenDrama,
|
||||||
required this.onMore,
|
required this.onMore,
|
||||||
this.playlists,
|
|
||||||
this.onOpenPlaylist,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final HomeFeedController feedController;
|
final HomeFeedController feedController;
|
||||||
final CategoryController categories;
|
final CategoryController categories;
|
||||||
final ValueChanged<Drama> onOpenDrama;
|
final ValueChanged<Drama> onOpenDrama;
|
||||||
final ValueChanged<RecommendSectionKind> onMore;
|
final ValueChanged<RecommendSectionKind> onMore;
|
||||||
final PlaylistController? playlists;
|
|
||||||
final ValueChanged<PlaylistDetail>? onOpenPlaylist;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final source = feedController.dramas;
|
final source = feedController.dramas;
|
||||||
final remote = playlists;
|
|
||||||
return AppPullToRefresh(
|
|
||||||
key: const Key('recommend-sections-refresh'),
|
|
||||||
onRefresh: () async {
|
|
||||||
await Future.wait([
|
|
||||||
feedController.refreshCurrent(),
|
|
||||||
categories.load(),
|
|
||||||
if (remote != null) remote.load(),
|
|
||||||
]);
|
|
||||||
},
|
|
||||||
child: NotificationListener<ScrollNotification>(
|
|
||||||
onNotification: (notification) =>
|
|
||||||
remote == null ? false : _onPlaylistScroll(notification, remote),
|
|
||||||
child: ListView(
|
|
||||||
key: const Key('recommend-sections-scroll'),
|
|
||||||
physics: AppPullToRefresh.physics,
|
|
||||||
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
|
|
||||||
children: remote == null
|
|
||||||
? _localSections(context, l10n, source)
|
|
||||||
: _remoteSections(context, l10n, remote),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Widget> _localSections(
|
|
||||||
BuildContext context,
|
|
||||||
AppLocalizations l10n,
|
|
||||||
List<Drama> source,
|
|
||||||
) {
|
|
||||||
final hits = recommendSectionDramas(
|
final hits = recommendSectionDramas(
|
||||||
kind: RecommendSectionKind.hits,
|
kind: RecommendSectionKind.hits,
|
||||||
source: source,
|
source: source,
|
||||||
@@ -82,7 +44,16 @@ class RecommendSectionsView extends StatelessWidget {
|
|||||||
kind: RecommendSectionKind.newReleases,
|
kind: RecommendSectionKind.newReleases,
|
||||||
source: source,
|
source: source,
|
||||||
);
|
);
|
||||||
return [
|
return AppPullToRefresh(
|
||||||
|
key: const Key('recommend-sections-refresh'),
|
||||||
|
onRefresh: () async {
|
||||||
|
await Future.wait([feedController.refreshCurrent(), categories.load()]);
|
||||||
|
},
|
||||||
|
child: ListView(
|
||||||
|
key: const Key('recommend-sections-scroll'),
|
||||||
|
physics: AppPullToRefresh.physics,
|
||||||
|
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
|
||||||
|
children: [
|
||||||
_section(
|
_section(
|
||||||
context,
|
context,
|
||||||
l10n,
|
l10n,
|
||||||
@@ -116,97 +87,9 @@ class RecommendSectionsView extends StatelessWidget {
|
|||||||
).take(_sectionPreviewCount).toList(),
|
).take(_sectionPreviewCount).toList(),
|
||||||
onMore: () => onMore(RecommendSectionKind.costume),
|
onMore: () => onMore(RecommendSectionKind.costume),
|
||||||
),
|
),
|
||||||
];
|
],
|
||||||
}
|
),
|
||||||
|
);
|
||||||
List<Widget> _remoteSections(
|
|
||||||
BuildContext context,
|
|
||||||
AppLocalizations l10n,
|
|
||||||
PlaylistController remote,
|
|
||||||
) {
|
|
||||||
if (!remote.loaded && remote.loading) {
|
|
||||||
return const [
|
|
||||||
SizedBox(
|
|
||||||
height: 240,
|
|
||||||
child: Center(
|
|
||||||
child: CircularProgressIndicator(
|
|
||||||
key: Key('recommend-playlists-loading'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
if (remote.items.isEmpty) {
|
|
||||||
return [
|
|
||||||
EmptyState(
|
|
||||||
key: const Key('recommend-playlists-empty'),
|
|
||||||
icon: Icons.video_library_outlined,
|
|
||||||
title: remote.error == null ? l10n.emptyContent : l10n.networkError,
|
|
||||||
actionLabel: l10n.retry,
|
|
||||||
onAction: remote.load,
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
final sections = <Widget>[];
|
|
||||||
for (final playlist in remote.items) {
|
|
||||||
if (sections.isNotEmpty) {
|
|
||||||
sections.add(const SizedBox(height: AppDimens.spaceXl));
|
|
||||||
}
|
|
||||||
sections.add(
|
|
||||||
_section(
|
|
||||||
context,
|
|
||||||
l10n,
|
|
||||||
key: playlist.id,
|
|
||||||
title: playlist.localizedName(
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
),
|
|
||||||
subtitle: playlist.localizedDescription(
|
|
||||||
Localizations.localeOf(context).languageCode,
|
|
||||||
),
|
|
||||||
dramas: playlist.dramas.take(_sectionPreviewCount).toList(),
|
|
||||||
onMore: () => onOpenPlaylist?.call(playlist),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (remote.loadingMore) {
|
|
||||||
sections.add(
|
|
||||||
const Padding(
|
|
||||||
padding: EdgeInsets.symmetric(vertical: AppDimens.spaceMd),
|
|
||||||
child: Center(
|
|
||||||
child: CircularProgressIndicator(
|
|
||||||
key: Key('recommend-playlists-more'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
} else if (!remote.hasMore) {
|
|
||||||
sections.add(
|
|
||||||
Padding(
|
|
||||||
key: const Key('paged-list-no-more'),
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
|
||||||
child: Text(
|
|
||||||
l10n.noMoreItems,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return sections;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _onPlaylistScroll(
|
|
||||||
ScrollNotification notification,
|
|
||||||
PlaylistController remote,
|
|
||||||
) {
|
|
||||||
if (notification.depth != 0) return false;
|
|
||||||
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
|
|
||||||
if (notification is! ScrollUpdateNotification &&
|
|
||||||
notification is! ScrollEndNotification) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
remote.loadMore();
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _section(
|
Widget _section(
|
||||||
|
|||||||
@@ -145,8 +145,6 @@ class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
|
|||||||
],
|
],
|
||||||
PagedListFooter(
|
PagedListFooter(
|
||||||
loading: controller.loadingMore,
|
loading: controller.loadingMore,
|
||||||
hasMore: controller.hasMore,
|
|
||||||
hasItems: controller.records.isNotEmpty,
|
|
||||||
errorMessage: controller.loadMoreError == null
|
errorMessage: controller.loadMoreError == null
|
||||||
? null
|
? null
|
||||||
: errorText(l10n, controller.loadMoreError, l10n.progressError),
|
: errorText(l10n, controller.loadMoreError, l10n.progressError),
|
||||||
|
|||||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user