feat(flutter): 增加目录加载诊断与前台重试

This commit is contained in:
Zhou Weidong committed 2026-10-20 18:17:36 +08:00
1 parent d68734cdab
commit 730a96559b
10 files changed
+268 -16

No files matched your search

+40 -7
View File
@@ -80,9 +80,17 @@ class AppConfig {
Future<bool> Function(String baseUrl)? probe,
String? fallbackBaseUrl,
}) async {
final candidateProbe = probe ?? _probeBaseUrl;
for (final candidate in _probeCandidates) {
if (await candidateProbe(candidate)) {
final result = probe == null
? await _probeBaseUrl(candidate)
: await _runInjectedProbe(candidate, probe);
if (kDebugMode) {
final status = result.ok
? 'ok'
: 'fail(${result.reason ?? 'request failed'})';
debugPrint('[probe] $candidate -> $status');
}
if (result.ok) {
applyRuntimeBaseUrl(candidate);
return;
}
@@ -90,25 +98,43 @@ class AppConfig {
applyRuntimeBaseUrl(fallbackBaseUrl ?? defaultBaseUrl);
}
static Future<bool> _probeBaseUrl(String baseUrl) async {
static Future<_ProbeResult> _runInjectedProbe(
String baseUrl,
Future<bool> Function(String baseUrl) probe,
) async {
try {
return _ProbeResult(ok: await probe(baseUrl));
} catch (error) {
return _ProbeResult(ok: false, reason: error.toString());
}
}
static Future<_ProbeResult> _probeBaseUrl(String baseUrl) async {
final client = HttpClient()..connectionTimeout = _probeTimeout;
try {
return await _requestCategories(
client,
Uri.parse('$baseUrl/app/categories'),
).timeout(_probeTimeout);
} catch (_) {
return false;
} catch (error) {
return _ProbeResult(ok: false, reason: error.toString());
} finally {
client.close(force: true);
}
}
static Future<bool> _requestCategories(HttpClient client, Uri uri) async {
static Future<_ProbeResult> _requestCategories(
HttpClient client,
Uri uri,
) async {
final request = await client.getUrl(uri);
final response = await request.close();
await response.drain<void>();
return response.statusCode == 200;
final ok = response.statusCode == 200;
return _ProbeResult(
ok: ok,
reason: ok ? null : 'HTTP ${response.statusCode}',
);
}
/// 后端返回的是相对路径(/files/...),这里补上服务地址。
@@ -118,3 +144,10 @@ class AppConfig {
return '$apiBaseUrl$path';
}
}
class _ProbeResult {
const _ProbeResult({required this.ok, this.reason});
final bool ok;
final String? reason;
}
+16 -2
View File
@@ -2,6 +2,7 @@
import 'package:flutter/foundation.dart';
import '../../config/app_config.dart';
import '../models/drama.dart';
import '../models/home_feed.dart';
import '../repositories/catalog_repository.dart';
@@ -22,6 +23,7 @@ class CatalogController extends ChangeNotifier {
/// 第一次首页请求结束后为 true。之后的重试不再回到开屏。
bool settled = false;
String? error;
String? debugError;
List<Drama> get dramas => feed.dramas;
List<FeedBanner> get banners => feed.banners;
@@ -30,13 +32,18 @@ class CatalogController extends ChangeNotifier {
Future<void> load() async {
loading = true;
error = null;
debugError = null;
notifyListeners();
try {
feed = await repository.fetchHomeFeed();
} on ApiException catch (exception) {
error = exception.message;
} catch (_) {
debugError = exception.toString();
_logFailure(exception);
} catch (exception) {
error = 'catalogError';
debugError = exception.toString();
_logFailure(exception);
} finally {
loading = false;
settled = true;
@@ -52,11 +59,18 @@ class CatalogController extends ChangeNotifier {
feed = await repository.fetchHomeFeed();
notifyListeners();
return true;
} catch (_) {
} catch (exception) {
_logFailure(exception);
return false;
}
}
void _logFailure(Object error) {
if (kDebugMode) {
debugPrint('[catalog] base=${AppConfig.apiBaseUrl} error=$error');
}
}
/// 需要完整剧集时补一次详情;已加载过则直接返回,避免重复请求。
Future<Drama> requireDetail(Drama drama) async {
if (drama.detailLoaded) return drama;
+12
View File
@@ -0,0 +1,12 @@
// Author: fruit.com.cn
import '../../config/app_config.dart';
/// 重新探测服务地址后再加载指定目录数据。
Future<void> retryCatalogLoad({
required Future<void> Function() reload,
Future<void> Function()? probe,
}) async {
await (probe ?? AppConfig.probeAndApplyBaseUrl)();
await reload();
}
@@ -2,6 +2,7 @@
import 'package:flutter/foundation.dart';
import '../../config/app_config.dart';
import '../models/content_category.dart';
import '../models/drama.dart';
import '../models/home_feed.dart';
@@ -17,6 +18,7 @@ class CategoryController extends ChangeNotifier {
HomeFeed feed = const HomeFeed();
bool loading = false;
String? error;
String? debugError;
bool _disposed = false;
/// 分类九宫格点击后读取该分类的剧目;缺失分区返回空列表。
@@ -32,6 +34,7 @@ class CategoryController extends ChangeNotifier {
Future<void> load() async {
loading = true;
error = null;
debugError = null;
_notify();
try {
final results = await Future.wait<Object>([
@@ -40,8 +43,12 @@ class CategoryController extends ChangeNotifier {
]);
categories = results[0] as List<ContentCategory>;
feed = results[1] as HomeFeed;
} catch (_) {
} catch (exception) {
error = 'categoriesError';
debugError = exception.toString();
if (kDebugMode) {
debugPrint('[catalog] base=${AppConfig.apiBaseUrl} error=$exception');
}
} finally {
loading = false;
_notify();
+47
View File
@@ -0,0 +1,47 @@
// Author: fruit.com.cn
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../config/app_config.dart';
import '../theme/app_colors.dart';
const TextStyle _debugStyle = TextStyle(
color: AppColors.subtle,
fontSize: 12,
height: 1.35,
);
/// 仅 debug 展示当前服务地址与目录请求的原始错误。
class CatalogDebugInfo extends StatelessWidget {
const CatalogDebugInfo({super.key, required this.error});
final String? error;
@override
Widget build(BuildContext context) {
if (!kDebugMode) return const SizedBox.shrink();
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'服务地址:${AppConfig.apiBaseUrl}',
key: const Key('catalog-debug-endpoint'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: _debugStyle,
),
const SizedBox(height: 2),
Text(
'错误:${error ?? 'unknown'}',
key: const Key('catalog-debug-error'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: _debugStyle,
),
],
);
}
}
+6
View File
@@ -25,6 +25,7 @@ class EmptyState extends StatelessWidget {
this.actionLabel,
this.actionKey,
this.onAction,
this.footer,
this.compact = false,
});
@@ -34,6 +35,7 @@ class EmptyState extends StatelessWidget {
final String? actionLabel;
final Key? actionKey;
final VoidCallback? onAction;
final Widget? footer;
final bool compact;
@override
@@ -65,6 +67,7 @@ class EmptyState extends StatelessWidget {
actionLabel: hasAction ? actionLabel : null,
actionKey: actionKey,
onAction: hasAction ? onAction : null,
footer: footer,
),
],
),
@@ -101,6 +104,7 @@ class _EmptyCopy extends StatelessWidget {
required this.actionLabel,
required this.actionKey,
required this.onAction,
required this.footer,
});
final String title;
@@ -108,6 +112,7 @@ class _EmptyCopy extends StatelessWidget {
final String? actionLabel;
final Key? actionKey;
final VoidCallback? onAction;
final Widget? footer;
@override
Widget build(BuildContext context) {
@@ -162,6 +167,7 @@ class _EmptyCopy extends StatelessWidget {
),
),
],
if (footer != null) ...[const SizedBox(height: 12), footer!],
],
);
}
+15 -3
View File
@@ -2,12 +2,14 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/repositories/search_repository.dart';
import '../../core/data/services/catalog_retry.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/formatting/error_text.dart';
import '../../core/theme/app_colors.dart';
@@ -15,6 +17,7 @@ import '../../core/theme/app_dimens.dart';
import '../../core/theme/app_theme.dart';
import '../../core/widgets/app_bottom_nav.dart';
import '../../core/widgets/app_pull_to_refresh.dart';
import '../../core/widgets/catalog_debug_info.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../filter/filter_page.dart';
@@ -253,7 +256,10 @@ class _DiscoverPageState extends State<DiscoverPage> {
title: errorText(l10n, error, l10n.categoriesError),
subtitle: l10n.emptyHint,
actionLabel: l10n.retry,
onAction: categories.load,
onAction: () => unawaited(_retryCategories(categories)),
footer: kDebugMode
? CatalogDebugInfo(error: categories.debugError ?? error)
: null,
),
),
];
@@ -503,8 +509,14 @@ class _DiscoverPageState extends State<DiscoverPage> {
Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => page));
}
Widget _block(Widget child) =>
SizedBox(height: 280, child: Center(child: child));
Widget _block(Widget child) => ConstrainedBox(
constraints: const BoxConstraints(minHeight: 280),
child: Center(child: child),
);
Future<void> _retryCategories(CategoryController categories) {
return retryCatalogLoad(reload: categories.load);
}
void _act(DiscoverPageAction action) {
logic.act(
+61 -3
View File
@@ -2,15 +2,20 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../core/config/app_config.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/services/catalog_controller.dart';
import '../../core/data/services/catalog_retry.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/platform/haptics.dart';
import '../../core/theme/app_theme.dart';
import '../../core/widgets/app_bottom_nav.dart';
import '../../core/widgets/catalog_debug_info.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../discover/discover_types.dart';
@@ -23,9 +28,57 @@ import '../mine/mine_view.dart';
import 'home_binding.dart';
import 'home_logic.dart';
class HomePage extends StatelessWidget {
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
bool _resumeRetryInFlight = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state != AppLifecycleState.resumed || _resumeRetryInFlight) return;
final catalog = context.read<CatalogController>();
final categories = context.read<CategoryController>();
if (catalog.error == null && categories.error == null) return;
unawaited(_retryAfterResume(catalog, categories));
}
Future<void> _retryAfterResume(
CatalogController catalog,
CategoryController categories,
) async {
_resumeRetryInFlight = true;
try {
await AppConfig.probeAndApplyBaseUrl();
await Future.wait([
if (catalog.error != null) catalog.load(),
if (categories.error != null) categories.load(),
]);
} finally {
_resumeRetryInFlight = false;
}
}
Future<void> _retryHome(CatalogController catalog) {
return retryCatalogLoad(reload: catalog.load);
}
@override
Widget build(BuildContext context) {
final catalog = context.watch<CatalogController>();
@@ -51,7 +104,10 @@ class HomePage extends StatelessWidget {
if (catalog.error != null) {
return Scaffold(
backgroundColor: Colors.transparent,
body: HomeFailureView(onRetry: catalog.load),
body: HomeFailureView(
error: catalog.debugError ?? catalog.error,
onRetry: () => unawaited(_retryHome(catalog)),
),
);
}
if (catalog.dramas.isEmpty) {
@@ -78,8 +134,9 @@ class HomePage extends StatelessWidget {
/// 首页目录加载失败与重试入口。
class HomeFailureView extends StatelessWidget {
const HomeFailureView({super.key, required this.onRetry});
const HomeFailureView({super.key, this.error, required this.onRetry});
final String? error;
final VoidCallback onRetry;
@override
@@ -90,6 +147,7 @@ class HomeFailureView extends StatelessWidget {
title: l10n.catalogError,
actionLabel: l10n.retry,
onAction: onRetry,
footer: kDebugMode ? CatalogDebugInfo(error: error) : null,
);
}
}
@@ -135,6 +135,9 @@ void main() {
expect(find.byKey(const Key('home-categories-error')), findsOneWidget);
expect(find.text('Retry'), findsOneWidget);
expect(find.byKey(const Key('catalog-debug-endpoint')), findsOneWidget);
expect(find.byKey(const Key('catalog-debug-error')), findsOneWidget);
expect(find.textContaining('discover feed unavailable'), findsOneWidget);
});
testWidgets('should_show_search_results_when_text_changes', (tester) async {
+60
View File
@@ -0,0 +1,60 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/config/app_config.dart';
import 'package:fruitshorts/core/data/services/catalog_retry.dart';
import 'package:fruitshorts/core/theme/app_colors.dart';
import 'package:fruitshorts/l10n/app_localizations.dart';
import 'package:fruitshorts/pages/home/home_view.dart';
void main() {
tearDown(AppConfig.clearRuntimeBaseUrl);
testWidgets('should_show_endpoint_and_raw_error_in_debug_failure', (
tester,
) async {
AppConfig.applyRuntimeBaseUrl('http://probe.test:8081');
await tester.pumpWidget(
MaterialApp(
locale: const Locale('en'),
supportedLocales: AppLocalizations.supportedLocales,
localizationsDelegates: AppLocalizations.localizationsDelegates,
home: Scaffold(
body: HomeFailureView(
error: 'SocketException: Connection refused',
onRetry: () {},
),
),
),
);
final endpoint = tester.widget<Text>(
find.byKey(const Key('catalog-debug-endpoint')),
);
expect(endpoint.data, '服务地址:http://probe.test:8081');
expect(endpoint.style?.fontSize, 12);
expect(endpoint.style?.color, AppColors.subtle);
expect(endpoint.maxLines, 2);
final error = tester.widget<Text>(
find.byKey(const Key('catalog-debug-error')),
);
expect(error.data, '错误:SocketException: Connection refused');
expect(error.style?.fontSize, 12);
expect(error.style?.color, AppColors.subtle);
expect(error.maxLines, 2);
});
test('should_probe_before_reloading_catalog', () async {
final steps = <String>[];
await retryCatalogLoad(
probe: () async => steps.add('probe'),
reload: () async => steps.add('load'),
);
expect(steps, ['probe', 'load']);
});
}