home_screen.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:math';
  4. import 'package:app_tracking_transparency/app_tracking_transparency.dart';
  5. import 'package:firebase_crashlytics/firebase_crashlytics.dart';
  6. import 'package:firebase_messaging/firebase_messaging.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter_svg/svg.dart';
  9. import 'package:fluttertoast/fluttertoast.dart';
  10. import 'package:logging/logging.dart';
  11. import 'package:provider/provider.dart';
  12. import 'package:puzzleweave/ads/applovin_ads_controller.dart';
  13. import 'package:puzzleweave/audio/jc_audio_controller.dart';
  14. import 'package:puzzleweave/collection/collection_screen.dart';
  15. import 'package:puzzleweave/config/config.dart';
  16. import 'package:puzzleweave/config/device.dart';
  17. import 'package:puzzleweave/firebase/adjust_helper.dart';
  18. import 'package:puzzleweave/homepage/home_board_play.dart';
  19. import 'package:puzzleweave/l10n/app_localizations.dart';
  20. import 'package:puzzleweave/models/cached_request.dart';
  21. import 'package:puzzleweave/models/download.dart';
  22. import 'package:puzzleweave/models/items.dart';
  23. import 'package:puzzleweave/persistence/persistence.dart';
  24. import 'package:puzzleweave/play/board_play.dart';
  25. import 'package:puzzleweave/settings/settings_screen.dart';
  26. import 'package:puzzleweave/skin/skin.dart';
  27. import 'package:puzzleweave/utils/mybutton.dart';
  28. import 'package:puzzleweave/utils/utils.dart';
  29. import '../ads/ad_helper.dart';
  30. import '../ads/ads_state.dart';
  31. import '../utils/memory_monitor.dart';
  32. final Logger _log = Logger('home_screen');
  33. class HomeScreen extends StatefulWidget {
  34. const HomeScreen({super.key});
  35. @override
  36. State<StatefulWidget> createState() => _HomeScreen();
  37. }
  38. const int minimumRemoteLoadCount = 30;
  39. class _HomeScreen extends AdsState<HomeScreen> with TickerProviderStateMixin {
  40. late Device device;
  41. late JcAudioController audio;
  42. List<ListItem>? latest;
  43. late CachedRequest latestCachedRequest;
  44. late StreamSubscription? latestSubscription;
  45. final _canvasKey = GlobalKey<HomeBoardPlayState>();
  46. final GlobalKey _collectionKey = GlobalKey();
  47. bool isLoading = true;
  48. bool firstRun = false;
  49. // ✅ 优化点1: 导航状态管理
  50. bool _isNavigating = false;
  51. // ✅ 优化点2: 防抖机制
  52. Timer? _refreshDebouncer;
  53. // ✅ 优化点3: 缓存计算结果
  54. double? _cachedCanvasWidth;
  55. double? _cachedCanvasHeight;
  56. bool _layoutCalculated = false;
  57. late AnimationController _collectionController;
  58. late Animation<double> _collectionAnimation;
  59. bool interPending = false;
  60. @override
  61. void initState() {
  62. super.initState();
  63. _log.info("首页初始化");
  64. _initializeComponents();
  65. _setupAnimations();
  66. _handleInitialNavigation();
  67. }
  68. void _initializeComponents() {
  69. device = context.read<Device>();
  70. audio = context.read<JcAudioController>();
  71. latestCachedRequest = data.latest;
  72. final cachedData = latestCachedRequest.cachedData;
  73. if (cachedData != null) {
  74. _onLatestDataUpdate(cachedData);
  75. }
  76. latestSubscription = latestCachedRequest.stream.listen(_onLatestDataUpdate, onError: _onLatestDataError);
  77. onInterstitialAdState = _createInterStateListener();
  78. }
  79. Function(AdState state) _createInterStateListener() {
  80. return (AdState state) {
  81. _log.info('Interstitial ad state changed: $state');
  82. if (state == AdState.dismissed && interPending) {
  83. _log.info('Interstitial ad dismissed, executing pending post-ad logic.');
  84. _canvasKey.currentState?.startFlipAnimation();
  85. final bool hasSufficientData = latest != null && latest!.length >= minimumRemoteLoadCount;
  86. final bool isNetworkActive = latestCachedRequest.hasRecentSuccessfulFetch;
  87. if (hasSufficientData) {
  88. if (isNetworkActive) {
  89. _log.info('Game finished, data complete & Network Active. Triggering sequential preloading...');
  90. _preloadNextImages();
  91. } else {
  92. _log.info('Game finished, data complete but Network inactive. Attempting refresh.');
  93. refresh();
  94. }
  95. } else {
  96. _log.info('Game finished, remote data incomplete. Attempting refresh...');
  97. refresh();
  98. }
  99. interPending = false;
  100. }
  101. };
  102. }
  103. void _setupAnimations() {
  104. _collectionController = AnimationController(duration: const Duration(milliseconds: 300), vsync: this)
  105. ..addStatusListener((status) {
  106. if (status == AnimationStatus.completed) {
  107. audio.playSfx(SfxType.pop);
  108. }
  109. });
  110. _collectionAnimation = TweenSequence<double>([
  111. TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.4).chain(CurveTween(curve: Curves.easeOut)), weight: 40.0),
  112. TweenSequenceItem(tween: Tween<double>(begin: 1.4, end: 1.0).chain(CurveTween(curve: Curves.easeIn)), weight: 60.0),
  113. ]).animate(_collectionController);
  114. }
  115. void _handleInitialNavigation() {
  116. if (Persistence().firstRun) {
  117. firstRun = true;
  118. WidgetsBinding.instance.addPostFrameCallback((_) {
  119. if (mounted && !_isNavigating) {
  120. _handleFirstRunNavigation();
  121. }
  122. });
  123. Persistence().firstRun = false;
  124. }
  125. WidgetsBinding.instance.addPostFrameCallback((_) {
  126. if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed && mounted) {
  127. audio.startMusic();
  128. }
  129. });
  130. }
  131. // ✅ 优化点4: 异步化首次运行导航
  132. void _handleFirstRunNavigation() {
  133. if (_isNavigating) return;
  134. _log.info('First run detected, navigating to initial play page.');
  135. final AssetItem initialItem = AssetItem(
  136. Config.firstId,
  137. '',
  138. 2000,
  139. 3000,
  140. 3,
  141. false,
  142. 'assets/builtin/${Config.firstId}.jpeg',
  143. 'assets/builtin/${Config.firstId}.jpeg',
  144. );
  145. return gotoPlay(initialItem, firstRun: true);
  146. }
  147. // ✅ 优化点5: 异步化文件检查
  148. void checkGoPlay() {
  149. if (currentItem == null || _isNavigating) return;
  150. Future.microtask(() async {
  151. try {
  152. final jsonFile = await localFile(currentItem!.jsonPath);
  153. final exists = await jsonFile.exists();
  154. if (mounted && exists && !_isNavigating) {
  155. gotoPlay(currentItem!);
  156. }
  157. } catch (e) {
  158. _log.warning('Error checking play file: $e');
  159. }
  160. });
  161. }
  162. @override
  163. void dispose() {
  164. _refreshDebouncer?.cancel();
  165. latestSubscription?.cancel();
  166. _collectionController.dispose();
  167. super.dispose();
  168. }
  169. // ✅ 优化点6: 简化数据更新逻辑
  170. _onLatestDataUpdate(datalist) {
  171. _log.info('_onLatestDataUpdate....');
  172. if (datalist == null) return;
  173. bool shouldCheckGoPlay = false;
  174. if (currentItem == null && !firstRun) {
  175. shouldCheckGoPlay = true;
  176. }
  177. latest = datalist as List<ListItem>;
  178. isLoading = false;
  179. setState(() {});
  180. final bool hasSufficientData = datalist.length >= minimumRemoteLoadCount;
  181. final bool isNetworkActive = latestCachedRequest.hasRecentSuccessfulFetch;
  182. if (hasSufficientData) {
  183. if (!hasInit) {
  184. initThird();
  185. }
  186. if (!isNetworkActive) {
  187. _debouncedRefresh();
  188. }
  189. } else {
  190. _log.info('Data insufficient (only ${datalist.length} items). Attempting refresh.');
  191. _debouncedRefresh();
  192. }
  193. if (shouldCheckGoPlay) {
  194. checkGoPlay();
  195. }
  196. }
  197. _onLatestDataError(error) {
  198. _log.info('_onLatestDataError.... $error');
  199. if (latest == null || latest!.isEmpty || latest!.length < 20) {
  200. _log.warning("_onLatestDataError, retry again");
  201. _debouncedRefresh();
  202. }
  203. }
  204. // ✅ 优化点7: 防抖刷新
  205. void _debouncedRefresh() {
  206. _refreshDebouncer?.cancel();
  207. _refreshDebouncer = Timer(const Duration(seconds: 2), () {
  208. if (mounted) {
  209. refresh();
  210. }
  211. });
  212. }
  213. Future<void> refresh() async {
  214. _log.info('refresh...');
  215. await latestCachedRequest.refresh();
  216. }
  217. ListItem? get currentItem {
  218. if (latest == null || latest!.isEmpty) {
  219. return null;
  220. }
  221. final Set<String> completedIds = data.completedWorks.value.map((work) => work.id).toSet();
  222. for (final item in latest!) {
  223. final String itemId = item.id;
  224. if (!completedIds.contains(itemId)) {
  225. _log.info('Found current item: $itemId');
  226. return item;
  227. }
  228. }
  229. _log.info('All items in the latest list have been completed.');
  230. return null;
  231. }
  232. // ✅ 优化点8: 后台预加载
  233. void _preloadNextImages() {
  234. Future.microtask(() async {
  235. const int totalPreloadCount = 20;
  236. if (latest == null || latest!.isEmpty || latest!.length < minimumRemoteLoadCount) {
  237. _log.info('Preload failed: latest list is empty.');
  238. return;
  239. }
  240. final Set<String> completedIds = data.completedWorks.value.map((work) => work.id).toSet();
  241. int startIndex = -1;
  242. for (int i = 0; i < latest!.length; i++) {
  243. if (!completedIds.contains(latest![i].id)) {
  244. startIndex = i;
  245. break;
  246. }
  247. }
  248. if (startIndex == -1) {
  249. _log.info('Preload: All images completed, nothing to preload.');
  250. return;
  251. }
  252. final int endPreloadIndex = min(startIndex + totalPreloadCount, latest!.length);
  253. final List<ListItem> itemsToLoad = latest!.sublist(startIndex, endPreloadIndex);
  254. if (itemsToLoad.isEmpty) {
  255. _log.info('Preload: No items found in the range.');
  256. return;
  257. }
  258. final ListItem currentItemToLoad = itemsToLoad.removeAt(0);
  259. itemsToLoad.add(currentItemToLoad);
  260. _log.info('Preloading ${itemsToLoad.length} images. Current item: ${currentItemToLoad.id} will be loaded last.');
  261. int preloadCount = 0;
  262. for (final item in itemsToLoad) {
  263. if (item is RemoteItem) {
  264. try {
  265. ItemLoader.preload(item, device.suggestedQuality);
  266. await Future.delayed(const Duration(milliseconds: 100));
  267. preloadCount++;
  268. } catch (e) {
  269. _log.warning('Failed to load item for preloading: ${item.id}, error: $e');
  270. }
  271. }
  272. }
  273. _log.info('Preload initiated for $preloadCount remote images, current item was last.');
  274. });
  275. }
  276. // ✅ 优化点9: 缓存布局计算
  277. void _calculateLayout() {
  278. if (_layoutCalculated) return;
  279. final double availableHeight = device.screenSize.height - device.appBarHeight - device.bannerHeight - 120;
  280. final double paddedWidth = device.screenSize.width - 2 * 30;
  281. final double paddedHeight = availableHeight;
  282. final double targetWidth = paddedWidth;
  283. final double targetHeight = targetWidth * device.aspectRatio;
  284. if (targetHeight > paddedHeight) {
  285. _cachedCanvasHeight = paddedHeight;
  286. _cachedCanvasWidth = paddedHeight / device.aspectRatio;
  287. } else {
  288. _cachedCanvasWidth = targetWidth;
  289. _cachedCanvasHeight = targetHeight;
  290. }
  291. _layoutCalculated = true;
  292. }
  293. @override
  294. Widget build(BuildContext context) {
  295. if (isLoading) return scrollableDummy;
  296. _calculateLayout();
  297. return Scaffold(
  298. backgroundColor: SkinHelper.colorWhite,
  299. appBar: AppBar(
  300. backgroundColor: SkinHelper.colorWhite,
  301. centerTitle: true,
  302. leading: RepaintBoundary(
  303. key: _collectionKey,
  304. child: ScaleTransition(
  305. scale: _collectionAnimation,
  306. child: IconButton(
  307. onPressed: () {
  308. audio.playSfx(SfxType.click);
  309. Navigator.push(context, CollectionScreen.buildRoute());
  310. },
  311. icon: const Icon(Icons.collections, color: Colors.black87),
  312. ),
  313. ),
  314. ),
  315. title: SvgPicture.asset(
  316. 'assets/images/title.svg',
  317. height: 32,
  318. placeholderBuilder: (BuildContext context) => const Text(
  319. 'Jigsort Solitaire',
  320. style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 24),
  321. ),
  322. ),
  323. actions: [
  324. IconButton(
  325. onPressed: () {
  326. audio.playSfx(SfxType.click);
  327. Navigator.push(context, SettingScreen.buildRoute());
  328. },
  329. icon: const Icon(Icons.settings, color: Colors.black87),
  330. ),
  331. ],
  332. ),
  333. body: Column(
  334. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  335. children: [
  336. if (Config.isDebug) MemoryMonitor.getMemoryWidget(),
  337. Expanded(
  338. child: Column(
  339. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  340. children: [
  341. Padding(
  342. padding: const EdgeInsets.symmetric(horizontal: 30),
  343. child: SizedBox(
  344. width: _cachedCanvasWidth!,
  345. height: _cachedCanvasHeight!,
  346. child: ValueListenableBuilder(
  347. valueListenable: data.completedWorks,
  348. builder: (context, value, child) {
  349. return HomeBoardPlay(
  350. key: _canvasKey,
  351. canvasWidth: _cachedCanvasWidth!,
  352. canvasHeight: _cachedCanvasHeight!,
  353. collectionKey: _collectionKey,
  354. onCollectionDone: () {
  355. _log.info('onCollectionDone, 启动合集收纳反馈动画');
  356. audio.playSfx(SfxType.appear);
  357. _collectionController.forward(from: 0.0);
  358. },
  359. );
  360. },
  361. ),
  362. ),
  363. ),
  364. playButton,
  365. ],
  366. ),
  367. ),
  368. SafeArea(
  369. child: SizedBox(
  370. height: context.read<Device>().bannerHeight,
  371. width: double.infinity,
  372. child: isBannerVisible ? getBanner('home_bottom') : const SizedBox.shrink(),
  373. ),
  374. ),
  375. ],
  376. ),
  377. );
  378. }
  379. // ✅ 优化点10: 导航状态管理
  380. void gotoPlay(ListItem item, {bool firstRun = false}) async {
  381. if (_isNavigating) {
  382. _log.info('Navigation already in progress, ignoring');
  383. return;
  384. }
  385. _log.info('goto play, firstRun = $firstRun');
  386. if (!mounted) return;
  387. _isNavigating = true;
  388. interPending = false;
  389. try {
  390. cleanBanner();
  391. if (!mounted) return;
  392. PageRouteBuilder? pageRouteBuilder = BoardPlay.buildRoute(item, firstRun: firstRun);
  393. final result = await Navigator.push(context, pageRouteBuilder);
  394. if (!mounted) return;
  395. // result 是 true, 说明关卡已经完成。 但此时可能播放插屏广告中, 需要等待用户关闭广告之后才能执行翻牌等逻辑
  396. if (result != null && result == true) {
  397. // 打印下当下的插屏广告状态
  398. _log.info('==================>interState = $intersState');
  399. if (intersState == AdState.ready && data.currentLevel % 25 != 0 && shouldShowInterstitialAd("level_done", data.currentLevel - 1)) {
  400. // 这种情况表示有插屏广告在播放,需要等待广告关闭之后才能执行翻牌动画等逻辑
  401. interPending = true;
  402. _log.info('Interstitial ad is currently playing, will execute post-ad logic after dismissal.');
  403. return;
  404. }
  405. _canvasKey.currentState?.startFlipAnimation();
  406. final bool hasSufficientData = latest != null && latest!.length >= minimumRemoteLoadCount;
  407. final bool isNetworkActive = latestCachedRequest.hasRecentSuccessfulFetch;
  408. if (hasSufficientData) {
  409. if (isNetworkActive) {
  410. _log.info('Game finished, data complete & Network Active. Triggering sequential preloading...');
  411. _preloadNextImages();
  412. } else {
  413. _log.info('Game finished, data complete but Network inactive. Attempting refresh.');
  414. refresh();
  415. }
  416. } else {
  417. _log.info('Game finished, remote data incomplete. Attempting refresh...');
  418. refresh();
  419. }
  420. }
  421. } finally {
  422. _isNavigating = false;
  423. }
  424. }
  425. Widget get playButton {
  426. return MyElevatedButton(
  427. width: device.isTablet ? 300 : 200,
  428. height: 70,
  429. borderRadius: BorderRadius.circular(20),
  430. gradient: LinearGradient(colors: [SkinHelper.coreBgColor, SkinHelper.slotBorderColor]),
  431. onPressed: () async {
  432. audio.playSfx(SfxType.click);
  433. if (currentItem != null) {
  434. gotoPlay(currentItem!);
  435. } else {
  436. Fluttertoast.showToast(
  437. msg: AppLocalizations.of(context)!.noMorePicture,
  438. toastLength: Toast.LENGTH_SHORT,
  439. gravity: ToastGravity.CENTER,
  440. timeInSecForIosWeb: 1,
  441. backgroundColor: SkinHelper.slotBorderColor,
  442. textColor: Colors.white,
  443. fontSize: 16.0,
  444. );
  445. }
  446. },
  447. child: Column(
  448. mainAxisAlignment: MainAxisAlignment.center,
  449. children: [
  450. Text(
  451. AppLocalizations.of(context)!.play,
  452. style: const TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
  453. ),
  454. Text('${AppLocalizations.of(context)!.level} ${data.currentLevel + 1}', style: const TextStyle(color: Colors.white, fontSize: 16)),
  455. ],
  456. ),
  457. );
  458. }
  459. Widget get scrollableDummy => Scaffold(
  460. backgroundColor: SkinHelper.colorWhite,
  461. body: Center(
  462. child: Column(
  463. mainAxisAlignment: MainAxisAlignment.center,
  464. children: [
  465. SizedBox(width: 40, height: 40, child: CircularProgressIndicator(strokeWidth: 3, valueColor: AlwaysStoppedAnimation<Color>(SkinHelper.coreBgColor))),
  466. const SizedBox(height: 20),
  467. Text(
  468. "Loading...",
  469. style: TextStyle(color: SkinHelper.slotBorderColor.withOpacity(0.7), fontSize: 14, fontWeight: FontWeight.w500),
  470. ),
  471. ],
  472. ),
  473. ),
  474. );
  475. ///////////////////////// 初始化相关 /////////////////////////
  476. static bool hasInit = false;
  477. void initThird() async {
  478. if (hasInit) return;
  479. hasInit = true;
  480. TrackingStatus attStatus = await AppTrackingTransparency.trackingAuthorizationStatus;
  481. if (attStatus == TrackingStatus.authorized && Platform.isIOS) {
  482. // ATT 通过之后,ios需要调用相关的原生sdk接口做进一步的初始化
  483. }
  484. initFCM();
  485. initAd();
  486. AdjustHelper.init(Persistence().uuid);
  487. final idfa = await AppTrackingTransparency.getAdvertisingIdentifier();
  488. _log.info("idfa: $idfa");
  489. }
  490. Future<bool> initATT() async {
  491. TrackingStatus status = await AppTrackingTransparency.trackingAuthorizationStatus;
  492. _log.info('initATT111 $status');
  493. if (status == TrackingStatus.notDetermined) {
  494. status = await AppTrackingTransparency.requestTrackingAuthorization();
  495. _log.info('initATT222 $status');
  496. }
  497. return status == TrackingStatus.authorized;
  498. }
  499. initAd() {
  500. _log.info('initAd');
  501. ApplovinAdsController applovinAdsController = context.read<ApplovinAdsController>();
  502. applovinAdsController.initialize();
  503. }
  504. initFCM() async {
  505. try {
  506. final fcmToken = await FirebaseMessaging.instance.getToken();
  507. _log.info("FCM Token: $fcmToken");
  508. FirebaseMessaging messaging = FirebaseMessaging.instance;
  509. NotificationSettings settings = await messaging.requestPermission(
  510. alert: true,
  511. announcement: false,
  512. badge: true,
  513. carPlay: false,
  514. criticalAlert: false,
  515. provisional: false,
  516. sound: true,
  517. );
  518. _log.warning('User granted permission: ${settings.authorizationStatus}');
  519. } catch (e) {
  520. FirebaseCrashlytics.instance.log("FCM FirebaseMessaging.instance.getToken error: $e");
  521. _log.warning(e);
  522. }
  523. }
  524. }