Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

fix: clean up flutter resource lifecycles

Predidit1aec7b1484c9
diff --git a/lib/bean/dialog/dialog_helper.dart b/lib/bean/dialog/dialog_helper.dart
index 074c2290..9c540ced 100644
--- a/lib/bean/dialog/dialog_helper.dart
+++ b/lib/bean/dialog/dialog_helper.dart
@@ -203,68 +203,105 @@ class KazumiDialog {
/// The caller is responsible for dismissing any currently-open dialog
/// BEFORE calling this method.
///
- /// [onComplete] is invoked inside [onDismiss] after the countdown finishes
- /// (or if the dialog is dismissed for any other reason), ensuring it runs
- /// exactly once and resources are always cleaned up.
+ /// [onComplete] is invoked after the dialog route finishes.
static void showTimedSuccessDialog({
required String title,
required String message,
required VoidCallback onComplete,
Duration duration = const Duration(seconds: 3),
}) {
- final progressNotifier = ValueNotifier<double>(0.0);
- Timer? countdownTimer;
- final totalMs = duration.inMilliseconds;
- final stopwatch = Stopwatch()..start();
- countdownTimer = Timer.periodic(const Duration(milliseconds: 16), (t) {
- final elapsed = stopwatch.elapsedMilliseconds;
- progressNotifier.value = (elapsed / totalMs).clamp(0.0, 1.0);
+ KazumiDialog.show<bool>(
+ clickMaskDismiss: false,
+ builder: (context) => _TimedSuccessDialog(
+ title: title,
+ message: message,
+ duration: duration,
+ ),
+ ).then((completed) {
+ if (completed == true) {
+ onComplete();
+ }
+ });
+ }
+}
+
+class _TimedSuccessDialog extends StatefulWidget {
+ const _TimedSuccessDialog({
+ required this.title,
+ required this.message,
+ required this.duration,
+ });
+
+ final String title;
+ final String message;
+ final Duration duration;
+
+ @override
+ State<_TimedSuccessDialog> createState() => _TimedSuccessDialogState();
+}
+
+class _TimedSuccessDialogState extends State<_TimedSuccessDialog> {
+ Timer? _countdownTimer;
+ late final Stopwatch _stopwatch = Stopwatch()..start();
+ double _progress = 0.0;
+
+ @override
+ void initState() {
+ super.initState();
+ _countdownTimer = Timer.periodic(const Duration(milliseconds: 16), (_) {
+ final totalMs = widget.duration.inMilliseconds.clamp(1, 1 << 31);
+ final elapsed = _stopwatch.elapsedMilliseconds;
+ final nextProgress = (elapsed / totalMs).clamp(0.0, 1.0).toDouble();
+ if (!mounted) return;
+ setState(() {
+ _progress = nextProgress;
+ });
if (elapsed >= totalMs) {
- t.cancel();
- KazumiDialog.dismiss();
+ _countdownTimer?.cancel();
+ _countdownTimer = null;
+ KazumiDialog.dismiss(popWith: true);
}
});
- KazumiDialog.show(
- clickMaskDismiss: false,
- onDismiss: () {
- countdownTimer?.cancel();
- progressNotifier.dispose();
- onComplete();
- },
- builder: (context) => Dialog(
- clipBehavior: Clip.antiAlias,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 28),
- child: SizedBox(
- width: 320,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(
- Icons.check_circle_rounded,
- size: 52,
- color: Theme.of(context).colorScheme.primary,
- ),
- const SizedBox(height: 16),
- Text(
- title,
- style: Theme.of(context).textTheme.titleLarge,
- ),
- const SizedBox(height: 6),
- Text(
- message,
- style: Theme.of(context).textTheme.bodyMedium,
- ),
- const SizedBox(height: 24),
- ValueListenableBuilder<double>(
- valueListenable: progressNotifier,
- builder: (context, value, _) => LinearProgressIndicator(
- value: value,
- borderRadius: BorderRadius.circular(4),
- ),
- ),
- ],
- ),
+ }
+
+ @override
+ void dispose() {
+ _countdownTimer?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 28),
+ child: SizedBox(
+ width: 320,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.check_circle_rounded,
+ size: 52,
+ color: Theme.of(context).colorScheme.primary,
+ ),
+ const SizedBox(height: 16),
+ Text(
+ widget.title,
+ style: Theme.of(context).textTheme.titleLarge,
+ ),
+ const SizedBox(height: 6),
+ Text(
+ widget.message,
+ style: Theme.of(context).textTheme.bodyMedium,
+ ),
+ const SizedBox(height: 24),
+ LinearProgressIndicator(
+ value: _progress,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ ],
),
),
),
diff --git a/lib/pages/bangumi/bangumi_setting.dart b/lib/pages/bangumi/bangumi_setting.dart
index 5dbf0673..817133e8 100644
--- a/lib/pages/bangumi/bangumi_setting.dart
+++ b/lib/pages/bangumi/bangumi_setting.dart
@@ -60,9 +60,7 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
return;
}
- final ValueNotifier<double?> progressValue = ValueNotifier<double?>(null);
- final ValueNotifier<String> progressText =
- ValueNotifier<String>('准备同步 Bangumi 状态...');
+ final progressDialogKey = GlobalKey<_BangumiSyncProgressDialogState>();
try {
setState(() {
@@ -71,56 +69,18 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
KazumiDialog.show(
clickMaskDismiss: false,
- builder: (context) {
- return PopScope(
- canPop: false,
- child: Dialog(
- child: Padding(
- padding: const EdgeInsets.all(20.0),
- child: SizedBox(
- width: 340,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const Text(
- 'Bangumi 同步进行中',
- style: TextStyle(
- fontSize: 16,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 12),
- ValueListenableBuilder<String>(
- valueListenable: progressText,
- builder: (_, value, __) => Text(value),
- ),
- const SizedBox(height: 12),
- ValueListenableBuilder<double?>(
- valueListenable: progressValue,
- builder: (_, value, __) =>
- LinearProgressIndicator(value: value),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- },
+ builder: (context) =>
+ _BangumiSyncProgressDialog(key: progressDialogKey),
);
final bangumi = BangumiSyncService();
await bangumi.ping();
await bangumi.syncCollectibles(
onProgress: (message, current, total) {
- progressText.value =
- total > 0 ? '$message ($current/$total)' : message;
- if (total > 0) {
- progressValue.value = (current / total).clamp(0.0, 1.0);
- } else {
- progressValue.value = null;
- }
+ progressDialogKey.currentState?.update(
+ total > 0 ? '$message ($current/$total)' : message,
+ total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
+ );
},
);
} catch (e) {
@@ -129,8 +89,6 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
if (KazumiDialog.observer.hasKazumiDialog) {
KazumiDialog.dismiss();
}
- progressValue.dispose();
- progressText.dispose();
if (mounted) {
setState(() {
syncCollectiblesing = false;
@@ -189,7 +147,8 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
},
title: Text('即时同步提示',
style: TextStyle(fontFamily: fontFamily)),
- description: Text('点击追番按钮触发即时同步时显示提示框', style: TextStyle(fontFamily: fontFamily)),
+ description: Text('点击追番按钮触发即时同步时显示提示框',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: bangumiImmediateSyncToastEnable,
),
SettingsTile.navigation(
@@ -202,12 +161,14 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
},
title: Text('同步优先级',
style: TextStyle(fontFamily: fontFamily)),
- description: Text('当本地与 Bangumi 状态不一致时优先使用哪个状态', style: TextStyle(fontFamily: fontFamily)),
+ description: Text('当本地与 Bangumi 状态不一致时优先使用哪个状态',
+ style: TextStyle(fontFamily: fontFamily)),
value: MenuAnchor(
consumeOutsideTap: true,
controller: syncPriorityMenuController,
builder: (context, controller, child) => Text(
- BangumiSyncPriority.fromValue(syncPriority).label,
+ BangumiSyncPriority.fromValue(syncPriority)
+ .label,
style: TextStyle(fontFamily: fontFamily)),
menuChildren: [
for (final entry in BangumiSyncPriority.values)
@@ -240,14 +201,17 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
? const SizedBox(
width: 20,
height: 20,
- child: CircularProgressIndicator(strokeWidth: 2),
+ child:
+ CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.sync_rounded),
onPressed: (_) async {
await syncWithProgress();
},
- title: Text("立即同步状态", style: TextStyle(fontFamily: fontFamily)),
- description: Text('同步状态不一致或仅存在于本地/远端的条目', style: TextStyle(fontFamily: fontFamily)),
+ title: Text("立即同步状态",
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('同步状态不一致或仅存在于本地/远端的条目',
+ style: TextStyle(fontFamily: fontFamily)),
),
],
),
@@ -280,55 +244,110 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
),
floatingActionButton: FloatingActionButton(
onPressed: isVerifying
- ? null
- : () async {
- final token = bangumiTokenController.text.trim();
- final bool bangumiSyncEnable =
- setting.get(SettingBoxKey.bangumiSyncEnable,
- defaultValue: false);
-
- if (token.isEmpty && bangumiSyncEnable) {
- KazumiDialog.showToast(message: 'Access Token 不能为空');
- return;
- }
- setState(() {
- isVerifying = true;
- });
- await setting.put(SettingBoxKey.bangumiAccessToken, token);
- final bangumi = BangumiSyncService();
+ ? null
+ : () async {
+ final token = bangumiTokenController.text.trim();
+ final bool bangumiSyncEnable = setting.get(
+ SettingBoxKey.bangumiSyncEnable,
+ defaultValue: false);
- if (token.isEmpty) {
- bangumi.reset();
- KazumiDialog.showToast(message: 'Bangumi Token 为空,请检查');
- if (!mounted) return;
+ if (token.isEmpty && bangumiSyncEnable) {
+ KazumiDialog.showToast(message: 'Access Token 不能为空');
+ return;
+ }
setState(() {
- isVerifying = false;
+ isVerifying = true;
});
- return;
- }
+ await setting.put(SettingBoxKey.bangumiAccessToken, token);
+ final bangumi = BangumiSyncService();
+
+ if (token.isEmpty) {
+ bangumi.reset();
+ KazumiDialog.showToast(message: 'Bangumi Token 为空,请检查');
+ if (!mounted) return;
+ setState(() {
+ isVerifying = false;
+ });
+ return;
+ }
+
+ KazumiDialog.showToast(message: '正在测试 Bangumi Token...');
+ try {
+ await bangumi.init();
+ } catch (e) {
+ KazumiDialog.showToast(message: '验证失败:${e.toString()}');
+ await setting.put(SettingBoxKey.bangumiSyncEnable, false);
+ if (!mounted) return;
+ setState(() {
+ isVerifying = false;
+ });
+ return;
+ }
- KazumiDialog.showToast(message: '正在测试 Bangumi Token...');
- try {
- await bangumi.init();
- } catch (e) {
- KazumiDialog.showToast(message: '验证失败:${e.toString()}');
- await setting.put(SettingBoxKey.bangumiSyncEnable, false);
+ KazumiDialog.showToast(
+ message: '测试成功,用户名:${bangumi.username}');
if (!mounted) return;
setState(() {
isVerifying = false;
});
- return;
- }
-
- KazumiDialog.showToast(message: '测试成功,用户名:${bangumi.username}');
- if (!mounted) return;
- setState(() {
- isVerifying = false;
- });
- },
+ },
child: const Icon(Icons.save),
),
),
);
}
}
+
+class _BangumiSyncProgressDialog extends StatefulWidget {
+ const _BangumiSyncProgressDialog({super.key});
+
+ @override
+ State<_BangumiSyncProgressDialog> createState() =>
+ _BangumiSyncProgressDialogState();
+}
+
+class _BangumiSyncProgressDialogState
+ extends State<_BangumiSyncProgressDialog> {
+ String _progressText = '准备同步 Bangumi 状态...';
+ double? _progressValue;
+
+ void update(String text, double? value) {
+ if (!mounted) return;
+ setState(() {
+ _progressText = text;
+ _progressValue = value;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return PopScope(
+ canPop: false,
+ child: Dialog(
+ child: Padding(
+ padding: const EdgeInsets.all(20.0),
+ child: SizedBox(
+ width: 340,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text(
+ 'Bangumi 同步进行中',
+ style: TextStyle(
+ fontSize: 16,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 12),
+ Text(_progressText),
+ const SizedBox(height: 12),
+ LinearProgressIndicator(value: _progressValue),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dart
index dc58699c..53b16d60 100644
--- a/lib/pages/collect/collect_page.dart
+++ b/lib/pages/collect/collect_page.dart
@@ -33,68 +33,29 @@ class _CollectPageState extends State<CollectPage>
Box setting = GStorage.setting;
Future<bool> _syncBangumiWithProgress({
- required ValueNotifier<double?> progressValue,
- required ValueNotifier<String> progressText,
+ required GlobalKey<_FullSyncProgressDialogState> progressDialogKey,
}) async {
- progressText.value = '准备同步 Bangumi 收藏...';
- progressValue.value = null;
+ progressDialogKey.currentState?.update('准备同步 Bangumi 收藏...', null);
await Future<void>.delayed(const Duration(milliseconds: 80));
return collectController.syncCollectiblesBangumi(
showSuccessToast: false,
onProgress: (message, current, total) {
- progressText.value = total > 0 ? '$message ($current/$total)' : message;
- if (total > 0) {
- progressValue.value = (current / total).clamp(0.0, 1.0);
- } else {
- progressValue.value = null;
- }
+ progressDialogKey.currentState?.update(
+ total > 0 ? '$message ($current/$total)' : message,
+ total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
+ );
},
);
}
void _showFullSyncProgressDialog({
- required ValueNotifier<double?> progressValue,
- required ValueNotifier<String> progressText,
+ required GlobalKey<_FullSyncProgressDialogState> progressDialogKey,
}) {
unawaited(KazumiDialog.show(
clickMaskDismiss: false,
- builder: (context) {
- return PopScope(
- canPop: false,
- child: Dialog(
- child: Padding(
- padding: const EdgeInsets.all(20.0),
- child: SizedBox(
- width: 340,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const Text(
- '收藏全量同步中',
- style:
- TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
- ),
- const SizedBox(height: 12),
- ValueListenableBuilder<String>(
- valueListenable: progressText,
- builder: (_, value, __) => Text(value),
- ),
- const SizedBox(height: 12),
- ValueListenableBuilder<double?>(
- valueListenable: progressValue,
- builder: (_, value, __) =>
- LinearProgressIndicator(value: value),
- ),
- ],
- ),
- ),
- ),
- ),
- );
- },
+ builder: (context) => _FullSyncProgressDialog(key: progressDialogKey),
));
}
@@ -123,13 +84,10 @@ class _CollectPageState extends State<CollectPage>
Future<void> _runFullSync({
required CollectSyncPlan plan,
}) async {
- final ValueNotifier<double?> progressValue = ValueNotifier<double?>(null);
- final ValueNotifier<String> progressText =
- ValueNotifier<String>('准备开始同步收藏...');
+ final progressDialogKey = GlobalKey<_FullSyncProgressDialogState>();
_showFullSyncProgressDialog(
- progressValue: progressValue,
- progressText: progressText,
+ progressDialogKey: progressDialogKey,
);
await Future<void>.delayed(const Duration(milliseconds: 80));
@@ -140,16 +98,14 @@ class _CollectPageState extends State<CollectPage>
try {
if (plan.shouldSyncWebDavCollectibles) {
- progressText.value = '正在同步 WebDav 收藏...';
- progressValue.value = null;
+ progressDialogKey.currentState?.update('正在同步 WebDav 收藏...', null);
webDavSynced =
await collectController.syncCollectibles(showSuccessToast: false);
}
if (plan.shouldSyncBangumi) {
bangumiSynced = await _syncBangumiWithProgress(
- progressValue: progressValue,
- progressText: progressText,
+ progressDialogKey: progressDialogKey,
);
}
@@ -157,8 +113,7 @@ class _CollectPageState extends State<CollectPage>
webDavSynced: webDavSynced,
bangumiSynced: bangumiSynced,
)) {
- progressText.value = '正在回传最新收藏到 WebDav...';
- progressValue.value = null;
+ progressDialogKey.currentState?.update('正在回传最新收藏到 WebDav...', null);
webDavUploaded = await collectController.uploadCollectiblesToWebDav(
showSuccessToast: false,
);
@@ -167,8 +122,6 @@ class _CollectPageState extends State<CollectPage>
if (KazumiDialog.observer.hasKazumiDialog) {
KazumiDialog.dismiss();
}
- progressValue.dispose();
- progressText.dispose();
}
KazumiDialog.showToast(
@@ -401,3 +354,56 @@ class _CollectPageState extends State<CollectPage>
return gridViewList;
}
}
+
+class _FullSyncProgressDialog extends StatefulWidget {
+ const _FullSyncProgressDialog({super.key});
+
+ @override
+ State<_FullSyncProgressDialog> createState() =>
+ _FullSyncProgressDialogState();
+}
+
+class _FullSyncProgressDialogState extends State<_FullSyncProgressDialog> {
+ String _progressText = '准备开始同步收藏...';
+ double? _progressValue;
+
+ void update(String text, double? value) {
+ if (!mounted) return;
+ setState(() {
+ _progressText = text;
+ _progressValue = value;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return PopScope(
+ canPop: false,
+ child: Dialog(
+ child: Padding(
+ padding: const EdgeInsets.all(20.0),
+ child: SizedBox(
+ width: 340,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text(
+ '收藏全量同步中',
+ style: TextStyle(
+ fontSize: 16,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 12),
+ Text(_progressText),
+ const SizedBox(height: 12),
+ LinearProgressIndicator(value: _progressValue),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index 056f5225..6b7209fd 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -81,10 +81,6 @@ class _SourceSheetState extends State<SourceSheet>
}
void showCaptchaDialog(Plugin plugin) {
- final captchaImageNotifier = ValueNotifier<String?>(null);
- final submittingNotifier = ValueNotifier<bool>(false);
- final TextEditingController codeController = TextEditingController();
-
/// flag whether verification has passed, used to distinguish normal dismissal from cancellation in onDismiss
bool verified = false;
@@ -100,19 +96,9 @@ class _SourceSheetState extends State<SourceSheet>
inputXpath: plugin.antiCrawlerConfig.captchaInput,
);
- final imageSub = _captchaProvider!.onCaptchaImageUrl.listen((url) {
- if (url != null) captchaImageNotifier.value = url;
- });
-
- Future<void> doSubmit() async {
- if (submittingNotifier.value) return;
- if (codeController.text.trim().isEmpty) {
- KazumiDialog.showToast(message: '请输入验证码');
- return;
- }
- submittingNotifier.value = true;
+ Future<void> submitCaptcha(String captchaCode) async {
await _captchaProvider?.submitCaptcha(
- captchaCode: codeController.text.trim(),
+ captchaCode: captchaCode.trim(),
inputXpath: plugin.antiCrawlerConfig.captchaInput,
buttonXpath: plugin.antiCrawlerConfig.captchaButton,
pluginName: plugin.name,
@@ -147,12 +133,6 @@ class _SourceSheetState extends State<SourceSheet>
onDismiss: () async {
_captchaVerifyTimer?.cancel();
_captchaVerifyTimer = null;
- // Cancel the image subscription before disposing the notifier to
- // prevent late stream events writing to an already-disposed notifier.
- imageSub.cancel();
- codeController.dispose();
- captchaImageNotifier.dispose();
- submittingNotifier.dispose();
// Capture the current provider instance locally NOW, before any await.
// Without this, an async gap could allow _captchaProvider to be
// replaced (or nulled by _SourceSheetState.dispose()), causing the
@@ -167,114 +147,11 @@ class _SourceSheetState extends State<SourceSheet>
provider?.dispose();
}
},
- builder: (context) {
- return Dialog(
- clipBehavior: Clip.antiAlias,
- child: Padding(
- padding: const EdgeInsets.all(24),
- child: SizedBox(
- width: 400,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Text(
- '验证码验证',
- style: Theme.of(context).textTheme.titleLarge,
- ),
- const SizedBox(height: 4),
- Text(
- '${plugin.name} 需要验证码验证',
- style: Theme.of(context).textTheme.bodySmall,
- ),
- const SizedBox(height: 20),
- ValueListenableBuilder<String?>(
- valueListenable: captchaImageNotifier,
- builder: (context, imageUrl, _) {
- if (imageUrl == null) {
- return const Column(
- children: [
- CircularProgressIndicator(),
- SizedBox(height: 12),
- Text('正在加载验证码图片...'),
- ],
- );
- }
- return ValueListenableBuilder<bool>(
- valueListenable: submittingNotifier,
- builder: (context, isSubmitting, _) {
- return Column(
- children: [
- ClipRRect(
- borderRadius: BorderRadius.circular(8),
- child: Image.memory(
- base64Decode(imageUrl.split(',').last),
- height: 80,
- fit: BoxFit.contain,
- errorBuilder: (context, error, _) =>
- const Text('图片解码失败'),
- ),
- ),
- const SizedBox(height: 16),
- TextField(
- controller: codeController,
- autofocus: true,
- enabled: !isSubmitting,
- decoration: const InputDecoration(
- labelText: '请输入验证码',
- border: OutlineInputBorder(),
- ),
- onSubmitted:
- isSubmitting ? null : (_) => doSubmit(),
- ),
- ],
- );
- },
- );
- },
- ),
- const SizedBox(height: 20),
- ListenableBuilder(
- listenable: Listenable.merge(
- [captchaImageNotifier, submittingNotifier]),
- builder: (context, _) {
- final isImageLoading = captchaImageNotifier.value == null;
- final isSubmitting = submittingNotifier.value;
- final isDisabled = isImageLoading || isSubmitting;
- return Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(
- color: Theme.of(context).colorScheme.outline),
- ),
- ),
- const SizedBox(width: 8),
- FilledButton(
- onPressed: isDisabled ? null : doSubmit,
- child: isSubmitting
- ? const SizedBox(
- width: 18,
- height: 18,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- ),
- )
- : const Text('提交'),
- ),
- ],
- );
- },
- ),
- ],
- ),
- ),
- ),
- );
- },
+ builder: (context) => _CaptchaDialog(
+ pluginName: plugin.name,
+ captchaImageStream: _captchaProvider!.onCaptchaImageUrl,
+ onSubmit: submitCaptcha,
+ ),
);
}
@@ -488,93 +365,45 @@ class _SourceSheetState extends State<SourceSheet>
KazumiDialog.showToast(message: '无可用别名,试试手动检索');
return;
}
- final aliasNotifier =
- ValueNotifier<List<String>>(widget.infoController.bangumiItem.alias);
- KazumiDialog.show(builder: (context) {
- return Dialog(
- clipBehavior: Clip.antiAlias,
- child: SizedBox(
- width: 560,
- child: ValueListenableBuilder<List<String>>(
- valueListenable: aliasNotifier,
- builder: (context, aliasList, child) {
- return ListView(
- shrinkWrap: true,
- children: aliasList.asMap().entries.map((entry) {
- final index = entry.key;
- final alias = entry.value;
- return ListTile(
- title: Text(alias),
- trailing: IconButton(
- onPressed: () {
- KazumiDialog.show(
- builder: (context) {
- return AlertDialog(
- title: const Text('删除确认'),
- content: const Text('删除后无法恢复,确认要永久删除这个别名吗?'),
- actions: [
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- },
- child: Text(
- '取消',
- style: TextStyle(
- color: Theme.of(context)
- .colorScheme
- .outline),
- ),
- ),
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- aliasList.removeAt(index);
- aliasNotifier.value = List.from(aliasList);
- collectController.updateLocalCollect(
- widget.infoController.bangumiItem);
- if (aliasList.isEmpty) {
- // pop whole dialog when empty
- Navigator.of(context).pop();
- }
- },
- child: const Text('确认'),
- ),
- ],
- );
- },
- );
- },
- icon: Icon(Icons.delete),
- ),
- onTap: () {
- KazumiDialog.dismiss();
- queryManager?.querySource(alias, pluginName);
- },
- );
- }).toList(),
- );
- },
- ),
- ),
- );
- });
+ KazumiDialog.show(
+ builder: (context) {
+ return _AliasDialog(
+ aliases: widget.infoController.bangumiItem.alias,
+ onAliasSelected: (alias) {
+ KazumiDialog.dismiss();
+ queryManager?.querySource(alias, pluginName);
+ },
+ onAliasesChanged: () {
+ collectController
+ .updateLocalCollect(widget.infoController.bangumiItem);
+ },
+ );
+ },
+ );
}
void showCustomSearchDialog(String pluginName) {
+ String customKeyword = '';
+
+ void submit(String value) {
+ final alias = value.trim();
+ if (alias.isEmpty) {
+ return;
+ }
+ widget.infoController.bangumiItem.alias.add(alias);
+ collectController.updateLocalCollect(widget.infoController.bangumiItem);
+ KazumiDialog.dismiss();
+ queryManager?.querySource(alias, pluginName);
+ }
+
KazumiDialog.show(
builder: (context) {
- final TextEditingController textController = TextEditingController();
return AlertDialog(
title: const Text('输入别名'),
content: TextField(
- controller: textController,
+ onChanged: (value) => customKeyword = value,
onSubmitted: (keyword) {
- if (textController.text != '') {
- widget.infoController.bangumiItem.alias
- .add(textController.text);
- KazumiDialog.dismiss();
- queryManager?.querySource(textController.text, pluginName);
- }
+ submit(keyword);
},
),
actions: [
@@ -589,14 +418,7 @@ class _SourceSheetState extends State<SourceSheet>
),
TextButton(
onPressed: () {
- if (textController.text != '') {
- widget.infoController.bangumiItem.alias
- .add(textController.text);
- collectController
- .updateLocalCollect(widget.infoController.bangumiItem);
- KazumiDialog.dismiss();
- queryManager?.querySource(textController.text, pluginName);
- }
+ submit(customKeyword);
},
child: const Text(
'确认',
@@ -748,3 +570,258 @@ class _SourceSheetState extends State<SourceSheet>
);
}
}
+
+class _CaptchaDialog extends StatefulWidget {
+ const _CaptchaDialog({
+ required this.pluginName,
+ required this.captchaImageStream,
+ required this.onSubmit,
+ });
+
+ final String pluginName;
+ final Stream<String?> captchaImageStream;
+ final Future<void> Function(String captchaCode) onSubmit;
+
+ @override
+ State<_CaptchaDialog> createState() => _CaptchaDialogState();
+}
+
+class _CaptchaDialogState extends State<_CaptchaDialog> {
+ final ValueNotifier<String?> _captchaImageNotifier =
+ ValueNotifier<String?>(null);
+ final ValueNotifier<bool> _submittingNotifier = ValueNotifier<bool>(false);
+ late final StreamSubscription<String?> _imageSub;
+ String _captchaCode = '';
+
+ @override
+ void initState() {
+ super.initState();
+ _imageSub = widget.captchaImageStream.listen((url) {
+ if (!mounted || url == null) return;
+ _captchaImageNotifier.value = url;
+ });
+ }
+
+ @override
+ void dispose() {
+ _imageSub.cancel();
+ _captchaImageNotifier.dispose();
+ _submittingNotifier.dispose();
+ super.dispose();
+ }
+
+ Future<void> _submit() async {
+ if (_submittingNotifier.value) return;
+ final captchaCode = _captchaCode.trim();
+ if (captchaCode.isEmpty) {
+ KazumiDialog.showToast(message: '请输入验证码');
+ return;
+ }
+ _submittingNotifier.value = true;
+ await widget.onSubmit(captchaCode);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: SizedBox(
+ width: 400,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Text(
+ '验证码验证',
+ style: Theme.of(context).textTheme.titleLarge,
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '${widget.pluginName} 需要验证码验证',
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ const SizedBox(height: 20),
+ ValueListenableBuilder<String?>(
+ valueListenable: _captchaImageNotifier,
+ builder: (context, imageUrl, _) {
+ if (imageUrl == null) {
+ return const Column(
+ children: [
+ CircularProgressIndicator(),
+ SizedBox(height: 12),
+ Text('正在加载验证码图片...'),
+ ],
+ );
+ }
+ return ValueListenableBuilder<bool>(
+ valueListenable: _submittingNotifier,
+ builder: (context, isSubmitting, _) {
+ return Column(
+ children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: Image.memory(
+ base64Decode(imageUrl.split(',').last),
+ height: 80,
+ fit: BoxFit.contain,
+ errorBuilder: (context, error, _) =>
+ const Text('图片解码失败'),
+ ),
+ ),
+ const SizedBox(height: 16),
+ TextField(
+ autofocus: true,
+ enabled: !isSubmitting,
+ onChanged: (value) => _captchaCode = value,
+ decoration: const InputDecoration(
+ labelText: '请输入验证码',
+ border: OutlineInputBorder(),
+ ),
+ onSubmitted: isSubmitting ? null : (_) => _submit(),
+ ),
+ ],
+ );
+ },
+ );
+ },
+ ),
+ const SizedBox(height: 20),
+ ListenableBuilder(
+ listenable: Listenable.merge([
+ _captchaImageNotifier,
+ _submittingNotifier,
+ ]),
+ builder: (context, _) {
+ final isImageLoading = _captchaImageNotifier.value == null;
+ final isSubmitting = _submittingNotifier.value;
+ final isDisabled = isImageLoading || isSubmitting;
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(
+ color: Theme.of(context).colorScheme.outline,
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ onPressed: isDisabled ? null : _submit,
+ child: isSubmitting
+ ? const SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ ),
+ )
+ : const Text('提交'),
+ ),
+ ],
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _AliasDialog extends StatefulWidget {
+ const _AliasDialog({
+ required this.aliases,
+ required this.onAliasSelected,
+ required this.onAliasesChanged,
+ });
+
+ final List<String> aliases;
+ final ValueChanged<String> onAliasSelected;
+ final VoidCallback onAliasesChanged;
+
+ @override
+ State<_AliasDialog> createState() => _AliasDialogState();
+}
+
+class _AliasDialogState extends State<_AliasDialog> {
+ late final ValueNotifier<List<String>> aliasNotifier =
+ ValueNotifier<List<String>>(List.from(widget.aliases));
+
+ @override
+ void dispose() {
+ aliasNotifier.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: SizedBox(
+ width: 560,
+ child: ValueListenableBuilder<List<String>>(
+ valueListenable: aliasNotifier,
+ builder: (context, aliasList, child) {
+ return ListView(
+ shrinkWrap: true,
+ children: aliasList.asMap().entries.map((entry) {
+ final index = entry.key;
+ final alias = entry.value;
+ return ListTile(
+ title: Text(alias),
+ trailing: IconButton(
+ onPressed: () {
+ KazumiDialog.show(
+ builder: (context) {
+ return AlertDialog(
+ title: const Text('删除确认'),
+ content: const Text('删除后无法恢复,确认要永久删除这个别名吗?'),
+ actions: [
+ TextButton(
+ onPressed: () {
+ KazumiDialog.dismiss();
+ },
+ child: Text(
+ '取消',
+ style: TextStyle(
+ color: Theme.of(context)
+ .colorScheme
+ .outline),
+ ),
+ ),
+ TextButton(
+ onPressed: () {
+ KazumiDialog.dismiss();
+ widget.aliases.removeAt(index);
+ aliasNotifier.value =
+ List.from(widget.aliases);
+ widget.onAliasesChanged();
+ if (widget.aliases.isEmpty) {
+ Navigator.of(this.context).pop();
+ }
+ },
+ child: const Text('确认'),
+ ),
+ ],
+ );
+ },
+ );
+ },
+ icon: Icon(Icons.delete),
+ ),
+ onTap: () => widget.onAliasSelected(alias),
+ );
+ }).toList(),
+ );
+ },
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/menu/menu.dart b/lib/pages/menu/menu.dart
index ea12a40b..483e012d 100644
--- a/lib/pages/menu/menu.dart
+++ b/lib/pages/menu/menu.dart
@@ -60,6 +60,12 @@ class NavigationBarState extends ChangeNotifier {
class _ScaffoldMenu extends State<ScaffoldMenu> {
final PageController _page = PageController();
+ @override
+ void dispose() {
+ _page.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
@@ -194,4 +200,4 @@ class _ScaffoldMenu extends State<ScaffoldMenu> {
),
);
}
-}
\ No newline at end of file
+}
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 073b50ee..01f4a28c 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -888,6 +888,7 @@ class _PlayerItemState extends State<PlayerItem>
!Platform.isLinux &&
!playerController.panel.brightnessSeeking) {
ScreenBrightnessPlatform.instance.application.then((value) {
+ if (!mounted) return;
playerController.panel.brightness = value;
});
}
@@ -1014,19 +1015,18 @@ class _PlayerItemState extends State<PlayerItem>
// 弹幕查询
void showDanmakuSwitch() {
+ String searchKeyword = videoPageController.title;
KazumiDialog.show(
builder: (context) {
- final TextEditingController searchTextController =
- TextEditingController();
- searchTextController.text = videoPageController.title;
return AlertDialog(
title: const Text('弹幕检索'),
- content: TextField(
- controller: searchTextController,
+ content: TextFormField(
+ initialValue: searchKeyword,
decoration: const InputDecoration(
hintText: '番剧名',
),
- onSubmitted: (keyword) {
+ onChanged: (value) => searchKeyword = value,
+ onFieldSubmitted: (keyword) {
showDanmakuSearchDialog(keyword);
},
),
@@ -1043,7 +1043,7 @@ class _PlayerItemState extends State<PlayerItem>
),
TextButton(
onPressed: () {
- showDanmakuSearchDialog(searchTextController.text);
+ showDanmakuSearchDialog(searchKeyword);
},
child: const Text(
'提交',
@@ -1285,16 +1285,16 @@ class _PlayerItemState extends State<PlayerItem>
onChanged: (String? newValue) {
if (newValue != null) {
if (newValue == defaultCustomSyncPlayEndPoint) {
- final serverTextController = TextEditingController();
+ String serverText = '';
KazumiDialog.show(
builder: (context) {
return AlertDialog(
title: const Text('自定义服务器'),
content: TextField(
- controller: serverTextController,
decoration: const InputDecoration(
hintText: '请输入服务器地址',
),
+ onChanged: (value) => serverText = value,
),
actions: <Widget>[
TextButton(
@@ -1306,16 +1306,13 @@ class _PlayerItemState extends State<PlayerItem>
TextButton(
child: const Text('确认'),
onPressed: () {
- if (serverTextController
- .text.isNotEmpty &&
- !syncPlayEndPoints.contains(
- serverTextController.text)) {
+ if (serverText.isNotEmpty &&
+ !syncPlayEndPoints
+ .contains(serverText)) {
KazumiDialog.dismiss();
setDialogState(() {
- customSyncPlayEndPoint =
- serverTextController.text;
- selectedSyncPlayEndPoint =
- serverTextController.text;
+ customSyncPlayEndPoint = serverText;
+ selectedSyncPlayEndPoint = serverText;
});
} else {
KazumiDialog.showToast(
@@ -1364,8 +1361,8 @@ class _PlayerItemState extends State<PlayerItem>
void showSyncPlayRoomCreateDialog() {
final formKey = GlobalKey<FormState>();
- final TextEditingController roomController = TextEditingController();
- final TextEditingController usernameController = TextEditingController();
+ String room = '';
+ String username = '';
KazumiDialog.show(builder: (BuildContext context) {
return AlertDialog(
title: const Text('加入房间'),
@@ -1375,11 +1372,11 @@ class _PlayerItemState extends State<PlayerItem>
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
- controller: roomController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '房间号',
),
+ onChanged: (value) => room = value,
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入房间号';
@@ -1393,10 +1390,10 @@ class _PlayerItemState extends State<PlayerItem>
),
const SizedBox(height: 16),
TextFormField(
- controller: usernameController,
decoration: const InputDecoration(
labelText: '用户名',
),
+ onChanged: (value) => username = value,
validator: (value) {
if (value == null || value.isEmpty) {
return '请输入用户名';
@@ -1422,8 +1419,8 @@ class _PlayerItemState extends State<PlayerItem>
onPressed: () {
if (formKey.currentState!.validate()) {
KazumiDialog.dismiss();
- playerController.createSyncPlayRoom(roomController.text,
- usernameController.text, widget.changeEpisode);
+ playerController.createSyncPlayRoom(
+ room, username, widget.changeEpisode);
}
},
child: const Text('确定'),
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index 55677225..3ec4e7d2 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -103,6 +103,13 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
static const double _danmakuIconSize = 24.0;
static const double _loadingIndicatorStrokeWidth = 2.0;
+ @override
+ void dispose() {
+ textController.dispose();
+ textFieldFocus.dispose();
+ super.dispose();
+ }
+
Widget get danmakuTextField {
return Container(
constraints: Utils.isDesktop()
@@ -1244,7 +1251,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
.castVideo(playerController.videoUrl,
videoPageController.currentPlugin.referer)
.whenComplete(() {
- if (needRestart) {
+ if (mounted && needRestart) {
playerController.play();
}
});
diff --git a/lib/pages/player/smallest_player_item_panel.dart b/lib/pages/player/smallest_player_item_panel.dart
index b6310a5d..1bb7148b 100644
--- a/lib/pages/player/smallest_player_item_panel.dart
+++ b/lib/pages/player/smallest_player_item_panel.dart
@@ -90,6 +90,12 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
static const double _danmakuIconSize = 24.0;
static const double _loadingIndicatorStrokeWidth = 2.0;
+ @override
+ void dispose() {
+ textController.dispose();
+ super.dispose();
+ }
+
void showForwardChange() {
KazumiDialog.show(builder: (context) {
String input = "";
@@ -898,7 +904,7 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
.castVideo(playerController.videoUrl,
videoPageController.currentPlugin.referer)
.whenComplete(() {
- if (needRestart) {
+ if (mounted && needRestart) {
playerController.play();
}
});
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index 94f1f26c..82b63cfe 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -81,6 +81,27 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaButtonController.text = plugin.antiCrawlerConfig.captchaButton;
}
+ @override
+ void dispose() {
+ apiController.dispose();
+ typeController.dispose();
+ nameController.dispose();
+ versionController.dispose();
+ userAgentController.dispose();
+ baseURLController.dispose();
+ searchURLController.dispose();
+ searchListController.dispose();
+ searchNameController.dispose();
+ searchResultController.dispose();
+ chapterRoadsController.dispose();
+ chapterResultController.dispose();
+ refererController.dispose();
+ captchaImageController.dispose();
+ captchaInputController.dispose();
+ captchaButtonController.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
final Plugin plugin = Modular.args.data as Plugin;
@@ -153,50 +174,67 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
const SizedBox(height: 20),
ExpansionTile(
title: const Text('高级选项'),
- shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.zero),
children: [
SettingsSection(
- title: Text('行为设置', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('行为设置',
+ style: TextStyle(fontFamily: fontFamily)),
tiles: [
SettingsTile.switchTile(
- title: Text('简易解析', style: TextStyle(fontFamily: fontFamily)),
- description: Text('使用简易解析器而不是现代解析器', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('简易解析',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('使用简易解析器而不是现代解析器',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: useLegacyParser,
- onToggle: (v) => setState(() => useLegacyParser = v ?? !useLegacyParser),
+ onToggle: (v) => setState(
+ () => useLegacyParser = v ?? !useLegacyParser),
),
SettingsTile.switchTile(
- title: Text('POST', style: TextStyle(fontFamily: fontFamily)),
- description: Text('使用 POST 而不是 GET 进行检索', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('POST',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('使用 POST 而不是 GET 进行检索',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: usePost,
- onToggle: (v) => setState(() => usePost = v ?? !usePost),
+ onToggle: (v) =>
+ setState(() => usePost = v ?? !usePost),
),
SettingsTile.switchTile(
- title: Text('内置播放器', style: TextStyle(fontFamily: fontFamily)),
- description: Text('使用内置播放器播放视频', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('内置播放器',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('使用内置播放器播放视频',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: useNativePlayer,
- onToggle: (v) => setState(() => useNativePlayer = v ?? !useNativePlayer),
+ onToggle: (v) => setState(
+ () => useNativePlayer = v ?? !useNativePlayer),
),
SettingsTile.switchTile(
- title: Text('广告过滤', style: TextStyle(fontFamily: fontFamily)),
- description: Text('启用 HLS 广告过滤', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('广告过滤',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('启用 HLS 广告过滤',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: adBlocker,
- onToggle: (v) => setState(() => adBlocker = v ?? !adBlocker),
+ onToggle: (v) =>
+ setState(() => adBlocker = v ?? !adBlocker),
),
],
),
SettingsSection(
- title: Text('网络设置', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('网络设置',
+ style: TextStyle(fontFamily: fontFamily)),
tiles: [
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
- context, info,
+ context,
+ info,
controller: userAgentController,
label: 'UserAgent',
),
),
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
- context, info,
+ context,
+ info,
controller: refererController,
label: 'Referer',
),
@@ -204,13 +242,17 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
],
),
SettingsSection(
- title: Text('反反爬虫配置', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('反反爬虫配置',
+ style: TextStyle(fontFamily: fontFamily)),
tiles: [
SettingsTile.switchTile(
- title: Text('启用反反爬虫', style: TextStyle(fontFamily: fontFamily)),
- description: Text('检索失败时显示验证码验证按钮而非重试', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('启用反反爬虫',
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text('检索失败时显示验证码验证按钮而非重试',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: antiCrawlerEnabled,
- onToggle: (v) => setState(() => antiCrawlerEnabled = v ?? !antiCrawlerEnabled),
+ onToggle: (v) => setState(() =>
+ antiCrawlerEnabled = v ?? !antiCrawlerEnabled),
),
if (antiCrawlerEnabled) ...[
SettingsTile.navigation(
@@ -221,7 +263,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaTypeMenuController.open();
}
},
- title: Text('验证类型', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('验证类型',
+ style: TextStyle(fontFamily: fontFamily)),
description: Text(
captchaType == CaptchaType.imageCaptcha
? '图片验证码(展示验证码图片,用户手动输入)'
@@ -239,17 +282,21 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
for (final entry in _captchaTypeMap.entries)
MenuItemButton(
requestFocusOnHover: false,
- onPressed: () => setState(() => captchaType = entry.key),
+ onPressed: () =>
+ setState(() => captchaType = entry.key),
child: Container(
height: 48,
- constraints: const BoxConstraints(minWidth: 160),
+ constraints:
+ const BoxConstraints(minWidth: 160),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
entry.value,
style: TextStyle(
color: entry.key == captchaType
- ? Theme.of(context).colorScheme.primary
+ ? Theme.of(context)
+ .colorScheme
+ .primary
: null,
fontFamily: fontFamily,
),
@@ -263,7 +310,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
if (captchaType == CaptchaType.imageCaptcha) ...[
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
- context, info,
+ context,
+ info,
controller: captchaImageController,
label: 'CaptchaImage (XPath)',
hint: '//img[@class="captcha"]',
@@ -272,7 +320,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
),
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
- context, info,
+ context,
+ info,
controller: captchaInputController,
label: 'CaptchaInput (XPath)',
hint: '//input[@name="captcha"]',
@@ -282,7 +331,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
],
CustomSettingsTile(
child: (info) => _buildTextFieldTile(
- context, info,
+ context,
+ info,
controller: captchaButtonController,
label: captchaType == CaptchaType.imageCaptcha
? 'CaptchaButton (XPath)'
@@ -337,7 +387,8 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
captchaInput: captchaInputController.text,
captchaButton: captchaButtonController.text,
));
- Modular.to.pushNamed('/settings/plugin/test', arguments: pluginText);
+ Modular.to
+ .pushNamed('/settings/plugin/test', arguments: pluginText);
},
),
SizedBox(width: 15),
diff --git a/lib/pages/plugin_editor/plugin_view_page.dart b/lib/pages/plugin_editor/plugin_view_page.dart
index 1e7d4b17..51f3e69b 100644
--- a/lib/pages/plugin_editor/plugin_view_page.dart
+++ b/lib/pages/plugin_editor/plugin_view_page.dart
@@ -78,45 +78,46 @@ class _PluginViewPageState extends State<PluginViewPage> {
}
void _showInputDialog() {
- final TextEditingController textController = TextEditingController();
- KazumiDialog.show(builder: (context) {
- return AlertDialog(
- title: const Text('导入规则'),
- content: StatefulBuilder(
- builder: (BuildContext context, StateSetter setState) {
- return TextField(
- controller: textController,
- );
- }),
- actions: [
- TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(color: Theme.of(context).colorScheme.outline),
- ),
- ),
- StatefulBuilder(
+ String pluginText = '';
+ KazumiDialog.show(
+ builder: (context) {
+ return AlertDialog(
+ title: const Text('导入规则'),
+ content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
- return TextButton(
- onPressed: () async {
- final String msg = textController.text;
- try {
- pluginsController.updatePlugin(Plugin.fromJson(
- json.decode(Utils.kazumiBase64ToJson(msg))));
- KazumiDialog.showToast(message: '导入成功');
- } catch (e) {
- KazumiDialog.dismiss();
- KazumiDialog.showToast(message: '导入失败 ${e.toString()}');
- }
- KazumiDialog.dismiss();
- },
- child: const Text('导入'),
+ return TextField(
+ onChanged: (value) => pluginText = value,
);
- })
- ],
- );
- });
+ }),
+ actions: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ StatefulBuilder(
+ builder: (BuildContext context, StateSetter setState) {
+ return TextButton(
+ onPressed: () async {
+ try {
+ pluginsController.updatePlugin(Plugin.fromJson(
+ json.decode(Utils.kazumiBase64ToJson(pluginText))));
+ KazumiDialog.showToast(message: '导入成功');
+ } catch (e) {
+ KazumiDialog.dismiss();
+ KazumiDialog.showToast(message: '导入失败 ${e.toString()}');
+ }
+ KazumiDialog.dismiss();
+ },
+ child: const Text('导入'),
+ );
+ })
+ ],
+ );
+ },
+ );
}
void onBackPressed(BuildContext context) {
diff --git a/lib/pages/popular/popular_page.dart b/lib/pages/popular/popular_page.dart
index c17687b0..270f81ee 100644
--- a/lib/pages/popular/popular_page.dart
+++ b/lib/pages/popular/popular_page.dart
@@ -55,6 +55,7 @@ class _PopularPageState extends State<PopularPage>
void dispose() {
_focusNode.dispose();
scrollController.removeListener(scrollListener);
+ scrollController.dispose();
super.dispose();
}
@@ -63,7 +64,8 @@ class _PopularPageState extends State<PopularPage>
if (scrollController.position.pixels >=
scrollController.position.maxScrollExtent - 200 &&
!popularController.isLoadingMore) {
- KazumiLogger().i('PopularPageController: Fetching next recommendation batch');
+ KazumiLogger()
+ .i('PopularPageController: Fetching next recommendation batch');
if (popularController.currentTag != '') {
popularController.queryBangumiByTag();
} else {
diff --git a/lib/pages/search/search_page.dart b/lib/pages/search/search_page.dart
index cf9957ac..d8abb492 100644
--- a/lib/pages/search/search_page.dart
+++ b/lib/pages/search/search_page.dart
@@ -48,7 +48,9 @@ class _SearchPageState extends State<SearchPage> {
@override
void dispose() {
searchPageController.bangumiList.clear();
+ searchController.dispose();
scrollController.removeListener(scrollListener);
+ scrollController.dispose();
super.dispose();
}
diff --git a/lib/pages/settings/danmaku/danmaku_shield_settings.dart b/lib/pages/settings/danmaku/danmaku_shield_settings.dart
index 176b3732..4bf3acbb 100644
--- a/lib/pages/settings/danmaku/danmaku_shield_settings.dart
+++ b/lib/pages/settings/danmaku/danmaku_shield_settings.dart
@@ -15,6 +15,12 @@ class _DanmakuShieldSettingsState extends State<DanmakuShieldSettings> {
final MyController myController = Modular.get<MyController>();
final TextEditingController textEditingController = TextEditingController();
+ @override
+ void dispose() {
+ textEditingController.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
return Scaffold(
diff --git a/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart b/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart
index 0d178d76..1a4d525b 100644
--- a/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart
+++ b/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart
@@ -7,13 +7,21 @@ class DanmakuShieldSettingsSheet extends StatefulWidget {
const DanmakuShieldSettingsSheet({super.key});
@override
- State<DanmakuShieldSettingsSheet> createState() => _DanmakuShieldSettingsSheetState();
+ State<DanmakuShieldSettingsSheet> createState() =>
+ _DanmakuShieldSettingsSheetState();
}
-class _DanmakuShieldSettingsSheetState extends State<DanmakuShieldSettingsSheet> {
+class _DanmakuShieldSettingsSheetState
+ extends State<DanmakuShieldSettingsSheet> {
final MyController myController = Modular.get<MyController>();
final TextEditingController textEditingController = TextEditingController();
+ @override
+ void dispose() {
+ textEditingController.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
return Scaffold(
diff --git a/lib/pages/settings/decoder_settings.dart b/lib/pages/settings/decoder_settings.dart
index 4a3386b2..f2e47f9d 100644
--- a/lib/pages/settings/decoder_settings.dart
+++ b/lib/pages/settings/decoder_settings.dart
@@ -18,6 +18,12 @@ class _DecoderSettingsState extends State<DecoderSettings> {
setting.get(SettingBoxKey.hardwareDecoder, defaultValue: 'auto-safe'),
);
+ @override
+ void dispose() {
+ decoder.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
@@ -29,11 +35,14 @@ class _DecoderSettingsState extends State<DecoderSettings> {
maxWidth: 1000,
sections: [
SettingsSection(
- title: Text('选择不受支持的解码器将回退到软件解码', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('选择不受支持的解码器将回退到软件解码',
+ style: TextStyle(fontFamily: fontFamily)),
tiles: hardwareDecodersList.entries
.map((e) => SettingsTile<String>.radioTile(
- title: Text(e.key, style: TextStyle(fontFamily: fontFamily)),
- description: Text(e.value, style: TextStyle(fontFamily: fontFamily)),
+ title:
+ Text(e.key, style: TextStyle(fontFamily: fontFamily)),
+ description: Text(e.value,
+ style: TextStyle(fontFamily: fontFamily)),
radioValue: e.key,
groupValue: decoder.value,
onChanged: (String? value) {
diff --git a/lib/pages/settings/displaymode_settings.dart b/lib/pages/settings/displaymode_settings.dart
index 86d68888..b085ed76 100644
--- a/lib/pages/settings/displaymode_settings.dart
+++ b/lib/pages/settings/displaymode_settings.dart
@@ -60,6 +60,13 @@ class _SetDisplayModeState extends State<SetDisplayMode> {
return f;
}
+ @override
+ void dispose() {
+ controller.dispose();
+ page.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
@@ -71,7 +78,8 @@ class _SetDisplayModeState extends State<SetDisplayMode> {
maxWidth: 1000,
sections: [
SettingsSection(
- title: Text('没有生效? 重启app试试', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('没有生效? 重启app试试',
+ style: TextStyle(fontFamily: fontFamily)),
tiles: modes
.map((e) => SettingsTile<DisplayMode>.radioTile(
radioValue: e,
@@ -85,8 +93,10 @@ class _SetDisplayModeState extends State<SetDisplayMode> {
await fetchAll();
},
title: e == DisplayMode.auto
- ? Text('自动', style: TextStyle(fontFamily: fontFamily))
- : Text('$e${e == active ? " [系统]" : ""}', style: TextStyle(fontFamily: fontFamily)),
+ ? Text('自动',
+ style: TextStyle(fontFamily: fontFamily))
+ : Text('$e${e == active ? " [系统]" : ""}',
+ style: TextStyle(fontFamily: fontFamily)),
))
.toList(),
),
diff --git a/lib/pages/settings/keyboard_settings.dart b/lib/pages/settings/keyboard_settings.dart
index 7e5d9959..f7238111 100644
--- a/lib/pages/settings/keyboard_settings.dart
+++ b/lib/pages/settings/keyboard_settings.dart
@@ -24,13 +24,15 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
@override
void initState() {
- super.initState();
+ super.initState();
// 根据默认快捷键生成可用快捷键列表,并读取已设置值
shortcuts = {
for (var key in defaultShortcuts.keys)
- key: (setting.get('shortcut_$key',
- defaultValue: defaultShortcuts[key]?.toList() ?? <String>[])
- ?.cast<String>() ?? [])
+ key: (setting
+ .get('shortcut_$key',
+ defaultValue: defaultShortcuts[key]?.toList() ?? <String>[])
+ ?.cast<String>() ??
+ [])
};
}
@@ -46,6 +48,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
focusNode.dispose();
super.dispose();
}
+
bool handleShortcutInput(String rawKey) {
if (listeningFunction == null || listeningIndex == null) return false;
@@ -84,6 +87,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
});
Future.delayed(const Duration(milliseconds: 50), () {
+ if (!mounted) return;
focusNode.requestFocus();
});
}
@@ -129,11 +133,10 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
},
child: ListView(
padding: const EdgeInsets.all(16),
- children:
- shortcuts.entries.map((entry) {
- final func = entry.key;
- final keys = entry.value;
- return Card(
+ children: shortcuts.entries.map((entry) {
+ final func = entry.key;
+ final keys = entry.value;
+ return Card(
margin: const EdgeInsets.symmetric(vertical: 8),
child: Padding(
padding: const EdgeInsets.all(12),
@@ -142,22 +145,21 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
children: [
Row(
children: [
- Text(
- shortcutsChineseName[func] ?? func,
- style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)
- ),
+ Text(shortcutsChineseName[func] ?? func,
+ style: const TextStyle(
+ fontSize: 18, fontWeight: FontWeight.bold)),
Spacer(),
IconButton(
icon: Icon(Icons.add),
onPressed: () {
- keys.removeWhere((key) => key.isEmpty || key == '...');
+ keys.removeWhere(
+ (key) => key.isEmpty || key == '...');
setState(() => keys.add(''));
setting.put('shortcut_$func', keys);
startListening(func, keys.length - 1);
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
- focusNode: FocusNode(canRequestFocus: false),
),
],
),
@@ -167,23 +169,27 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {
runSpacing: 8,
children: [
for (int i = 0; i < keys.length; i++)
- ActionChip(
- label: Text(keyAliases[keys[i]] ?? keys[i],),
- avatar: keys.length >=2 ?Icon(Icons.cancel) :Icon(Icons.edit),
- onPressed: (keys.length >=2)
- ?() {
- setState(() {
- keys.removeAt(i);
- listeningIndex = null;
- if (keys.length >1){
- keys.removeWhere((key) => key.isEmpty || key == '...');
- }
- setting.put('shortcut_$func', keys);
- });
- }
- :() => startListening(func, 0),
- focusNode: FocusNode(canRequestFocus: false),
- ),
+ ActionChip(
+ label: Text(
+ keyAliases[keys[i]] ?? keys[i],
+ ),
+ avatar: keys.length >= 2
+ ? Icon(Icons.cancel)
+ : Icon(Icons.edit),
+ onPressed: (keys.length >= 2)
+ ? () {
+ setState(() {
+ keys.removeAt(i);
+ listeningIndex = null;
+ if (keys.length > 1) {
+ keys.removeWhere((key) =>
+ key.isEmpty || key == '...');
+ }
+ setting.put('shortcut_$func', keys);
+ });
+ }
+ : () => startListening(func, 0),
+ ),
],
),
],
diff --git a/lib/pages/settings/renderer_settings.dart b/lib/pages/settings/renderer_settings.dart
index 5af434b5..6034cd00 100644
--- a/lib/pages/settings/renderer_settings.dart
+++ b/lib/pages/settings/renderer_settings.dart
@@ -18,6 +18,12 @@ class _RendererSettingsState extends State<RendererSettings> {
setting.get(SettingBoxKey.androidVideoRenderer, defaultValue: 'auto'),
);
+ @override
+ void dispose() {
+ renderer.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
diff --git a/lib/pages/settings/super_resolution_settings.dart b/lib/pages/settings/super_resolution_settings.dart
index acdeb610..19a4d99b 100644
--- a/lib/pages/settings/super_resolution_settings.dart
+++ b/lib/pages/settings/super_resolution_settings.dart
@@ -28,6 +28,12 @@ class _SuperResolutionSettingsState extends State<SuperResolutionSettings> {
setting.get(SettingBoxKey.superResolutionWarn, defaultValue: false);
}
+ @override
+ void dispose() {
+ superResolutionType.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
final fontFamily = Theme.of(context).textTheme.bodyMedium?.fontFamily;
@@ -39,12 +45,13 @@ class _SuperResolutionSettingsState extends State<SuperResolutionSettings> {
maxWidth: 1000,
sections: [
SettingsSection(
- title: Text(
- '超分辨率需要启用硬件解码, 若启用硬件解码后仍然不生效, 尝试切换视频渲染器为 gpu', style: TextStyle(fontFamily: fontFamily)),
+ title: Text('超分辨率需要启用硬件解码, 若启用硬件解码后仍然不生效, 尝试切换视频渲染器为 gpu',
+ style: TextStyle(fontFamily: fontFamily)),
tiles: [
SettingsTile<String>.radioTile(
title: Text("OFF", style: TextStyle(fontFamily: fontFamily)),
- description: Text("默认禁用超分辨率", style: TextStyle(fontFamily: fontFamily)),
+ description: Text("默认禁用超分辨率",
+ style: TextStyle(fontFamily: fontFamily)),
radioValue: "1",
groupValue: superResolutionType.value,
onChanged: (String? value) {
@@ -58,8 +65,10 @@ class _SuperResolutionSettingsState extends State<SuperResolutionSettings> {
},
),
SettingsTile<String>.radioTile(
- title: Text("Efficiency", style: TextStyle(fontFamily: fontFamily)),
- description: Text("默认启用基于Anime4K的超分辨率 (效率优先)", style: TextStyle(fontFamily: fontFamily)),
+ title: Text("Efficiency",
+ style: TextStyle(fontFamily: fontFamily)),
+ description: Text("默认启用基于Anime4K的超分辨率 (效率优先)",
+ style: TextStyle(fontFamily: fontFamily)),
radioValue: "2",
groupValue: superResolutionType.value,
onChanged: (String? value) {
@@ -73,8 +82,10 @@ class _SuperResolutionSettingsState extends State<SuperResolutionSettings> {
},
),
SettingsTile<String>.radioTile(
- title: Text("Quality", style: TextStyle(fontFamily: fontFamily)),
- description: Text("默认启用基于Anime4K的超分辨率 (质量优先)", style: TextStyle(fontFamily: fontFamily)),
+ title:
+ Text("Quality", style: TextStyle(fontFamily: fontFamily)),
+ description: Text("默认启用基于Anime4K的超分辨率 (质量优先)",
+ style: TextStyle(fontFamily: fontFamily)),
radioValue: "3",
groupValue: superResolutionType.value,
onChanged: (String? value) {
@@ -93,7 +104,8 @@ class _SuperResolutionSettingsState extends State<SuperResolutionSettings> {
tiles: [
SettingsTile.switchTile(
title: Text('关闭提示', style: TextStyle(fontFamily: fontFamily)),
- description: Text('关闭每次启用超分辨率时的提示', style: TextStyle(fontFamily: fontFamily)),
+ description: Text('关闭每次启用超分辨率时的提示',
+ style: TextStyle(fontFamily: fontFamily)),
initialValue: promptOnEnable,
onToggle: (value) async {
promptOnEnable = value ?? !promptOnEnable;
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index 0e186ccd..48d40b35 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -226,7 +226,7 @@ class _VideoPageState extends State<VideoPage>
windowManager.removeListener(this);
} catch (_) {}
try {
- observerController.controller?.dispose();
+ scrollController.dispose();
} catch (_) {}
try {
animation.dispose();
@@ -253,6 +253,7 @@ class _VideoPageState extends State<VideoPage>
videoPageController.resetEpisodeComments();
videoPageController.resetOfflineMode();
Utils.unlockScreenRotation();
+ keyboardFocus.dispose();
tabController.dispose();
TimedShutdownService().cancel();
super.dispose();
@@ -497,7 +498,7 @@ class _VideoPageState extends State<VideoPage>
}
void showMobileDanmakuInput() {
- final TextEditingController textController = TextEditingController();
+ String danmakuText = '';
showModalBottomSheet(
shape: const BeveledRectangleBorder(),
isScrollControlled: true,
@@ -518,9 +519,9 @@ class _VideoPageState extends State<VideoPage>
constraints: const BoxConstraints(maxHeight: 34),
child: TextField(
style: const TextStyle(fontSize: 15),
- controller: textController,
autofocus: true,
textAlignVertical: TextAlignVertical.center,
+ onChanged: (value) => danmakuText = value,
decoration: const InputDecoration(
filled: true,
floatingLabelBehavior: FloatingLabelBehavior.never,
@@ -536,7 +537,6 @@ class _VideoPageState extends State<VideoPage>
),
onSubmitted: (msg) {
showDanmakuDestinationPickerAndSend(msg);
- textController.clear();
Navigator.pop(context);
},
),
@@ -544,10 +544,8 @@ class _VideoPageState extends State<VideoPage>
),
IconButton(
onPressed: () {
- final msg = textController.text;
Navigator.pop(context);
- showDanmakuDestinationPickerAndSend(msg);
- textController.clear();
+ showDanmakuDestinationPickerAndSend(danmakuText);
},
icon: Icon(
Icons.send_rounded,
diff --git a/lib/pages/webdav_editor/webdav_editor_page.dart b/lib/pages/webdav_editor/webdav_editor_page.dart
index 45e56f7e..b9c42868 100644
--- a/lib/pages/webdav_editor/webdav_editor_page.dart
+++ b/lib/pages/webdav_editor/webdav_editor_page.dart
@@ -34,6 +34,14 @@ class _WebDavEditorPageState extends State<WebDavEditorPage> {
setting.get(SettingBoxKey.webDavPassword, defaultValue: '');
}
+ @override
+ void dispose() {
+ webDavURLController.dispose();
+ webDavUsernameController.dispose();
+ webDavPasswordController.dispose();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) {
return Scaffold(
diff --git a/lib/utils/timed_shutdown_service.dart b/lib/utils/timed_shutdown_service.dart
index edb12133..78b64ac8 100644
--- a/lib/utils/timed_shutdown_service.dart
+++ b/lib/utils/timed_shutdown_service.dart
@@ -5,22 +5,24 @@ import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/utils/logger.dart';
class TimedShutdownService {
- static final TimedShutdownService _instance = TimedShutdownService._internal();
+ static final TimedShutdownService _instance =
+ TimedShutdownService._internal();
factory TimedShutdownService() => _instance;
TimedShutdownService._internal();
Timer? _shutdownTimer;
int _remainingSeconds = 0;
bool _isDialogShowing = false;
+
/// Last set minutes, used for repeat functionality
int _lastSetMinutes = 0;
/// Callback to invoke when timer expires (e.g., pause video)
VoidCallback? _onExpiredCallback;
-
+
/// Remaining time in seconds notifier
final ValueNotifier<int> remainingSecondsNotifier = ValueNotifier<int>(0);
-
+
/// Currently set minutes notifier (for UI display)
final ValueNotifier<int> setMinutesNotifier = ValueNotifier<int>(0);
@@ -29,7 +31,7 @@ class TimedShutdownService {
/// Currently set minutes (0 = disabled)
int get setMinutes => setMinutesNotifier.value;
-
+
/// Remaining time in seconds
int get remainingSeconds => remainingSecondsNotifier.value;
@@ -44,14 +46,14 @@ class TimedShutdownService {
remainingSecondsNotifier.value = _remainingSeconds;
setMinutesNotifier.value = minutes;
_onExpiredCallback = onExpired;
-
+
// Update remaining time every second (runs globally, not tied to playback)
_shutdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (_remainingSeconds > 0) {
_remainingSeconds--;
remainingSecondsNotifier.value = _remainingSeconds;
}
-
+
if (_remainingSeconds <= 0) {
timer.cancel();
_shutdownTimer = null;
@@ -79,7 +81,7 @@ class TimedShutdownService {
if (setMinutesNotifier.value != 0) {
setMinutesNotifier.value = 0;
}
-
+
// If dialog is showing, dismiss it
if (_isDialogShowing) {
KazumiDialog.dismiss();
@@ -91,14 +93,15 @@ class TimedShutdownService {
void _onTimerExpired() {
// Reset UI state so it doesn't show 00:00
setMinutesNotifier.value = 0;
-
+
// Invoke the callback if set (e.g., pause video)
try {
_onExpiredCallback?.call();
} catch (e) {
- KazumiLogger().e('TimedShutdownService: onExpired callback failed', error: e);
+ KazumiLogger()
+ .e('TimedShutdownService: onExpired callback failed', error: e);
}
-
+
_showTimerExpiredDialog();
}
@@ -173,96 +176,152 @@ class TimedShutdownService {
VoidCallback? onExpired,
void Function(int)? onResult,
}) {
- int selectedHours = 0;
- int selectedMinutes = 0;
-
KazumiDialog.show(
- builder: (context) {
- return StatefulBuilder(
- builder: (context, setState) {
- return AlertDialog(
- title: Text(title),
- content: SizedBox(
- height: 200,
- child: Row(
- children: [
- // Hours picker
- Expanded(
- child: Column(
- children: [
- const Text('时', style: TextStyle(fontSize: 14)),
- const SizedBox(height: 8),
- Expanded(
- child: CupertinoPicker(
- scrollController: FixedExtentScrollController(initialItem: selectedHours),
- itemExtent: 40,
- onSelectedItemChanged: (index) {
- setState(() => selectedHours = index);
- },
- children: List.generate(25, (index) => Center(
- child: Text(index.toString().padLeft(2, '0'), style: const TextStyle(fontSize: 20)),
- )),
- ),
+ builder: (context) => _CustomTimerDialog(
+ title: title,
+ autoStart: autoStart,
+ onExpired: onExpired,
+ onResult: onResult,
+ ),
+ );
+ }
+}
+
+class _CustomTimerDialog extends StatefulWidget {
+ const _CustomTimerDialog({
+ required this.title,
+ required this.autoStart,
+ required this.onExpired,
+ required this.onResult,
+ });
+
+ final String title;
+ final bool autoStart;
+ final VoidCallback? onExpired;
+ final void Function(int)? onResult;
+
+ @override
+ State<_CustomTimerDialog> createState() => _CustomTimerDialogState();
+}
+
+class _CustomTimerDialogState extends State<_CustomTimerDialog> {
+ late final FixedExtentScrollController _hoursController;
+ late final FixedExtentScrollController _minutesController;
+ int _selectedHours = 0;
+ int _selectedMinutes = 0;
+
+ @override
+ void initState() {
+ super.initState();
+ _hoursController = FixedExtentScrollController(initialItem: _selectedHours);
+ _minutesController =
+ FixedExtentScrollController(initialItem: _selectedMinutes);
+ }
+
+ @override
+ void dispose() {
+ _hoursController.dispose();
+ _minutesController.dispose();
+ super.dispose();
+ }
+
+ void _confirm() {
+ final totalMinutes = _selectedHours * 60 + _selectedMinutes;
+ if (totalMinutes <= 0) {
+ KazumiDialog.showToast(message: '请选择有效的时间');
+ return;
+ }
+ KazumiDialog.dismiss();
+ if (widget.autoStart) {
+ TimedShutdownService().start(totalMinutes, onExpired: widget.onExpired);
+ KazumiDialog.showToast(
+ message:
+ '已设置 ${TimedShutdownService().formatMinutesToDisplay(totalMinutes)} 后定时关闭',
+ );
+ }
+ widget.onResult?.call(totalMinutes);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AlertDialog(
+ title: Text(widget.title),
+ content: SizedBox(
+ height: 200,
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ children: [
+ const Text('时', style: TextStyle(fontSize: 14)),
+ const SizedBox(height: 8),
+ Expanded(
+ child: CupertinoPicker(
+ scrollController: _hoursController,
+ itemExtent: 40,
+ onSelectedItemChanged: (index) {
+ setState(() => _selectedHours = index);
+ },
+ children: List.generate(
+ 25,
+ (index) => Center(
+ child: Text(
+ index.toString().padLeft(2, '0'),
+ style: const TextStyle(fontSize: 20),
),
- ],
+ ),
),
),
- const Text(':', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
- // Minutes picker
- Expanded(
- child: Column(
- children: [
- const Text('分', style: TextStyle(fontSize: 14)),
- const SizedBox(height: 8),
- Expanded(
- child: CupertinoPicker(
- scrollController: FixedExtentScrollController(initialItem: selectedMinutes),
- itemExtent: 40,
- onSelectedItemChanged: (index) {
- setState(() => selectedMinutes = index);
- },
- children: List.generate(60, (index) => Center(
- child: Text(index.toString().padLeft(2, '0'), style: const TextStyle(fontSize: 20)),
- )),
- ),
+ ),
+ ],
+ ),
+ ),
+ const Text(
+ ':',
+ style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
+ ),
+ Expanded(
+ child: Column(
+ children: [
+ const Text('分', style: TextStyle(fontSize: 14)),
+ const SizedBox(height: 8),
+ Expanded(
+ child: CupertinoPicker(
+ scrollController: _minutesController,
+ itemExtent: 40,
+ onSelectedItemChanged: (index) {
+ setState(() => _selectedMinutes = index);
+ },
+ children: List.generate(
+ 60,
+ (index) => Center(
+ child: Text(
+ index.toString().padLeft(2, '0'),
+ style: const TextStyle(fontSize: 20),
),
- ],
+ ),
),
),
- ],
- ),
- ),
- actions: [
- TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(color: Theme.of(context).colorScheme.outline),
),
- ),
- TextButton(
- onPressed: () {
- final totalMinutes = selectedHours * 60 + selectedMinutes;
- if (totalMinutes <= 0) {
- KazumiDialog.showToast(message: '请选择有效的时间');
- return;
- }
- KazumiDialog.dismiss();
- if (autoStart) {
- TimedShutdownService().start(totalMinutes, onExpired: onExpired);
- KazumiDialog.showToast(
- message: '已设置 ${TimedShutdownService().formatMinutesToDisplay(totalMinutes)} 后定时关闭',
- );
- }
- onResult?.call(totalMinutes);
- },
- child: const Text('确定'),
- ),
- ],
- );
- },
- );
- },
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(),
+ child: Text(
+ '取消',
+ style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ ),
+ ),
+ TextButton(
+ onPressed: _confirm,
+ child: const Text('确定'),
+ ),
+ ],
);
}
}
diff --git a/lib/webview/video/impl/video_webview_android_impl.dart b/lib/webview/video/impl/video_webview_android_impl.dart
index c5933fed..910b9c25 100644
--- a/lib/webview/video/impl/video_webview_android_impl.dart
+++ b/lib/webview/video/impl/video_webview_android_impl.dart
@@ -284,6 +284,7 @@ class VideoWebviewAndroidImpl
headlessWebView?.dispose();
headlessWebView = null;
webviewController = null;
+ disposeEventControllers();
}
Future<void> _setupProxy() async {
diff --git a/lib/webview/video/impl/video_webview_apple_impl.dart b/lib/webview/video/impl/video_webview_apple_impl.dart
index a78d0e82..b7a8f680 100644
--- a/lib/webview/video/impl/video_webview_apple_impl.dart
+++ b/lib/webview/video/impl/video_webview_apple_impl.dart
@@ -114,7 +114,8 @@ class VideoWebviewAppleImpl
logEventController.add('loading completed: $url');
},
onReceivedError: (controller, request, error) {
- KazumiLogger().e('WebView: error: ${error.toString()} - Request: ${request.url}');
+ KazumiLogger().e(
+ 'WebView: error: ${error.toString()} - Request: ${request.url}');
},
),
);
@@ -199,8 +200,7 @@ class VideoWebviewAppleImpl
}
}
- Future<void> addUserScripts(
- bool useLegacyParser) async {
+ Future<void> addUserScripts(bool useLegacyParser) async {
final List<UserScript> scripts = [];
if (useLegacyParser) {
@@ -327,5 +327,6 @@ class VideoWebviewAppleImpl
headlessWebView?.dispose();
headlessWebView = null;
webviewController = null;
+ disposeEventControllers();
}
}
diff --git a/lib/webview/video/impl/video_webview_impl.dart b/lib/webview/video/impl/video_webview_impl.dart
index bb04ef08..4780ad12 100644
--- a/lib/webview/video/impl/video_webview_impl.dart
+++ b/lib/webview/video/impl/video_webview_impl.dart
@@ -40,8 +40,7 @@ class VideoWebviewImpl
if (_isAdUrl(lower)) return null;
if (_isM3U8Url(lower) ||
_isRangeVideoRequest(lower, request.headers)) {
- logEventController
- .add('Native intercepted video URL: $url');
+ logEventController.add('Native intercepted video URL: $url');
isIframeLoaded = true;
isVideoSourceLoaded = true;
videoLoadingEventController.add(false);
@@ -67,8 +66,8 @@ class VideoWebviewImpl
'Console [${consoleMessage.messageLevel}]: ${consoleMessage.message}');
},
onReceivedError: (controller, request, error) {
- logEventController.add(
- 'Error: ${error.description} - ${request.url}');
+ logEventController
+ .add('Error: ${error.description} - ${request.url}');
},
),
);
@@ -427,8 +426,8 @@ class VideoWebviewImpl
Future<void> unloadPage() async {
videoParserTimer?.cancel();
videoParserTimer = null;
- await webviewController
- ?.loadUrl(urlRequest: URLRequest(url: WebUri("about:blank")));
+ await webviewController?.loadUrl(
+ urlRequest: URLRequest(url: WebUri("about:blank")));
}
@override
@@ -438,6 +437,7 @@ class VideoWebviewImpl
headlessWebView?.dispose();
headlessWebView = null;
webviewController = null;
+ disposeEventControllers();
}
bool _isM3U8Url(String lower) {
diff --git a/lib/webview/video/impl/video_webview_linux_impl.dart b/lib/webview/video/impl/video_webview_linux_impl.dart
index 31f25cea..fa31051c 100644
--- a/lib/webview/video/impl/video_webview_linux_impl.dart
+++ b/lib/webview/video/impl/video_webview_linux_impl.dart
@@ -83,8 +83,10 @@ class VideoWebviewLinuxImpl extends VideoWebviewController<Webview> {
@override
void dispose() {
- webviewController!.close();
+ webviewController?.close();
+ webviewController = null;
bridgeInited = false;
+ disposeEventControllers();
}
Future<void> initJSBridge(bool useLegacyParser) async {
diff --git a/lib/webview/video/impl/video_webview_windows_impl.dart b/lib/webview/video/impl/video_webview_windows_impl.dart
index 9804b951..c2f89df0 100644
--- a/lib/webview/video/impl/video_webview_windows_impl.dart
+++ b/lib/webview/video/impl/video_webview_windows_impl.dart
@@ -104,6 +104,7 @@ class VideoWebviewWindowsImpl
subscriptions.clear();
headlessWebview?.dispose();
headlessWebview = null;
+ disposeEventControllers();
}
// The webview_windows package does not have a method to unload the current page.
diff --git a/lib/webview/video/video_webview_controller.dart b/lib/webview/video/video_webview_controller.dart
index 8cb3f51b..a31b654a 100644
--- a/lib/webview/video/video_webview_controller.dart
+++ b/lib/webview/video/video_webview_controller.dart
@@ -45,11 +45,26 @@ abstract class VideoWebviewController<T> {
final StreamController<(String, int)> videoParserEventController =
StreamController<(String, int)>.broadcast();
- Stream<(String, int)> get onVideoURLParser => videoParserEventController.stream;
+ Stream<(String, int)> get onVideoURLParser =>
+ videoParserEventController.stream;
+
+ void disposeEventControllers() {
+ if (!initEventController.isClosed) {
+ initEventController.close();
+ }
+ if (!logEventController.isClosed) {
+ logEventController.close();
+ }
+ if (!videoLoadingEventController.isClosed) {
+ videoLoadingEventController.close();
+ }
+ if (!videoParserEventController.isClosed) {
+ videoParserEventController.close();
+ }
+ }
/// Webview load URL method
- Future<void> loadUrl(String url, bool useLegacyParser,
- {int offset = 0});
+ Future<void> loadUrl(String url, bool useLegacyParser, {int offset = 0});
/// Webview unload page method
Future<void> unloadPage();