You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
samples/game_template/lib/main.dart

288 lines
10 KiB

// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Uncomment the following lines when enabling Firebase Crashlytics
// import 'dart:io';
// import 'package:firebase_core/firebase_core.dart';
// import 'package:firebase_crashlytics/firebase_crashlytics.dart';
// import 'package:flutter/foundation.dart';
// import 'firebase_options.dart';
import 'dart:developer' as dev;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'src/ads/ads_controller.dart';
import 'src/app_lifecycle/app_lifecycle.dart';
import 'src/audio/audio_controller.dart';
import 'src/games_services/games_services.dart';
import 'src/games_services/score.dart';
import 'src/in_app_purchase/in_app_purchase.dart';
import 'src/level_selection/level_selection_screen.dart';
import 'src/level_selection/levels.dart';
import 'src/main_menu/main_menu_screen.dart';
import 'src/play_session/play_session_screen.dart';
import 'src/player_progress/persistence/local_storage_player_progress_persistence.dart';
import 'src/player_progress/persistence/player_progress_persistence.dart';
import 'src/player_progress/player_progress.dart';
import 'src/settings/persistence/local_storage_settings_persistence.dart';
import 'src/settings/persistence/settings_persistence.dart';
import 'src/settings/settings.dart';
import 'src/settings/settings_screen.dart';
import 'src/style/my_transition.dart';
import 'src/style/palette.dart';
import 'src/style/snack_bar.dart';
import 'src/win_game/win_game_screen.dart';
Future<void> main() async {
// Subscribe to log messages.
Logger.root.onRecord.listen((record) {
dev.log(
record.message,
time: record.time,
level: record.level.value,
name: record.loggerName,
zone: record.zone,
error: record.error,
stackTrace: record.stackTrace,
);
});
WidgetsFlutterBinding.ensureInitialized();
// TODO: To enable Firebase Crashlytics, uncomment the following line.
// See the 'Crashlytics' section of the main README.md file for details.
// if (!kIsWeb && (Platform.isIOS || Platform.isAndroid)) {
// try {
// await Firebase.initializeApp(
// options: DefaultFirebaseOptions.currentPlatform,
// );
//
// FlutterError.onError = (errorDetails) {
// FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
// };
//
// // Pass all uncaught asynchronous errors
// // that aren't handled by the Flutter framework to Crashlytics.
// PlatformDispatcher.instance.onError = (error, stack) {
// FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
// return true;
// };
// } catch (e) {
// debugPrint("Firebase couldn't be initialized: $e");
// }
// }
_log.info('Going full screen');
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.edgeToEdge,
);
// TODO: When ready, uncomment the following lines to enable integrations.
// Read the README for more info on each integration.
AdsController? adsController;
// if (!kIsWeb && (Platform.isIOS || Platform.isAndroid)) {
// /// Prepare the google_mobile_ads plugin so that the first ad loads
// /// faster. This can be done later or with a delay if startup
// /// experience suffers.
// adsController = AdsController(MobileAds.instance);
// adsController.initialize();
// }
GamesServicesController? gamesServicesController;
// if (!kIsWeb && (Platform.isIOS || Platform.isAndroid)) {
// gamesServicesController = GamesServicesController()
// // Attempt to log the player in.
// ..initialize();
// }
InAppPurchaseController? inAppPurchaseController;
// if (!kIsWeb && (Platform.isIOS || Platform.isAndroid)) {
// inAppPurchaseController = InAppPurchaseController(InAppPurchase.instance)
// // Subscribing to [InAppPurchase.instance.purchaseStream] as soon
// // as possible in order not to miss any updates.
// ..subscribe();
// // Ask the store what the player has bought already.
// inAppPurchaseController.restorePurchases();
// }
runApp(
MyApp(
settingsPersistence: LocalStorageSettingsPersistence(),
playerProgressPersistence: LocalStoragePlayerProgressPersistence(),
inAppPurchaseController: inAppPurchaseController,
adsController: adsController,
gamesServicesController: gamesServicesController,
),
);
}
Logger _log = Logger('main.dart');
class MyApp extends StatelessWidget {
static final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) =>
const MainMenuScreen(key: Key('main menu')),
routes: [
GoRoute(
path: 'play',
pageBuilder: (context, state) => buildMyTransition<void>(
key: ValueKey('play'),
child: const LevelSelectionScreen(
key: Key('level selection'),
),
color: context.watch<Palette>().backgroundLevelSelection,
),
routes: [
GoRoute(
path: 'session/:level',
pageBuilder: (context, state) {
Bump go_router from 6.5.9 to 7.0.0 in /game_template (#1761) Bumps [go_router](https://github.com/flutter/packages/tree/main/packages) from 6.5.9 to 7.0.0. <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/flutter/packages/commit/b01736711cc7c2034baa4254ed95566a8c70bb83"><code>b017367</code></a> [go_router] Cleans up route match API and introduces dart fix (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3819">#3819</a>)</li> <li><a href="https://github.com/flutter/packages/commit/2f95ecda81649d667871420ff8049b7f09e14bef"><code>2f95ecd</code></a> [camerax] Add <code>LifecycleOwner</code> Proxy (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3837">#3837</a>)</li> <li><a href="https://github.com/flutter/packages/commit/815cfca847dfdb340fd947538f0ba234f81f61b6"><code>815cfca</code></a> [file_selector] Add getDirectoryPaths implementation for Windows (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3704">#3704</a>)</li> <li><a href="https://github.com/flutter/packages/commit/6dc28c9c3f0f5098ce62dd5c87cf77ea0dab08d4"><code>6dc28c9</code></a> [various] Update Android example min SDKs (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3847">#3847</a>)</li> <li><a href="https://github.com/flutter/packages/commit/1a90429ac139d4471543925ecc67a3bf28592df2"><code>1a90429</code></a> [camerax] Implement Image Streaming (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3454">#3454</a>)</li> <li><a href="https://github.com/flutter/packages/commit/124e330a2bdd45f8b4a98089aff717e34a14b8f8"><code>124e330</code></a> [various] update agp and gradle for all examples in packages (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3822">#3822</a>)</li> <li><a href="https://github.com/flutter/packages/commit/c71747df2c11c54ccc03dc4c3b9b470153ede43c"><code>c71747d</code></a> Update xcode to 14c18 (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3774">#3774</a>)</li> <li><a href="https://github.com/flutter/packages/commit/3dc59f914df812da4790b1a6b36d7ec6b0df2d7c"><code>3dc59f9</code></a> [camera_android] Add NV21 as an image stream format <a href="https://github.com/flutter/packages/tree/main/packages/issues/3277">#3277</a> (<a href="https://github.com/flutter/packages/tree/main/packages/issues/3639">#3639</a>)</li> <li>See full diff in <a href="https://github.com/flutter/packages/commits/go_router-v7.0.0/packages">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=go_router&package-manager=pub&previous-version=6.5.9&new-version=7.0.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Brett Morgan <brettmorgan@google.com>
2 years ago
final levelNumber =
int.parse(state.pathParameters['level']!);
final level = gameLevels
.singleWhere((e) => e.number == levelNumber);
return buildMyTransition<void>(
key: ValueKey('level'),
child: PlaySessionScreen(
level,
key: const Key('play session'),
),
color: context.watch<Palette>().backgroundPlaySession,
);
},
),
GoRoute(
path: 'won',
redirect: (context, state) {
if (state.extra == null) {
// Trying to navigate to a win screen without any data.
// Possibly by using the browser's back button.
return '/';
}
// Otherwise, do not redirect.
return null;
},
pageBuilder: (context, state) {
final map = state.extra! as Map<String, dynamic>;
final score = map['score'] as Score;
return buildMyTransition<void>(
key: ValueKey('won'),
child: WinGameScreen(
score: score,
key: const Key('win game'),
),
color: context.watch<Palette>().backgroundPlaySession,
);
},
)
]),
GoRoute(
path: 'settings',
builder: (context, state) =>
const SettingsScreen(key: Key('settings')),
),
]),
],
);
final PlayerProgressPersistence playerProgressPersistence;
final SettingsPersistence settingsPersistence;
final GamesServicesController? gamesServicesController;
final InAppPurchaseController? inAppPurchaseController;
final AdsController? adsController;
const MyApp({
required this.playerProgressPersistence,
required this.settingsPersistence,
required this.inAppPurchaseController,
required this.adsController,
required this.gamesServicesController,
super.key,
});
@override
Widget build(BuildContext context) {
return AppLifecycleObserver(
child: MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) {
var progress = PlayerProgress(playerProgressPersistence);
progress.getLatestFromStore();
return progress;
},
),
Provider<GamesServicesController?>.value(
value: gamesServicesController),
Provider<AdsController?>.value(value: adsController),
ChangeNotifierProvider<InAppPurchaseController?>.value(
value: inAppPurchaseController),
Provider<SettingsController>(
lazy: false,
create: (context) => SettingsController(
persistence: settingsPersistence,
)..loadStateFromPersistence(),
),
ProxyProvider2<SettingsController, ValueNotifier<AppLifecycleState>,
AudioController>(
// Ensures that the AudioController is created on startup,
// and not "only when it's needed", as is default behavior.
// This way, music starts immediately.
lazy: false,
create: (context) => AudioController()..initialize(),
update: (context, settings, lifecycleNotifier, audio) {
if (audio == null) throw ArgumentError.notNull();
audio.attachSettings(settings);
audio.attachLifecycleNotifier(lifecycleNotifier);
return audio;
},
dispose: (context, audio) => audio.dispose(),
),
Provider(
create: (context) => Palette(),
),
],
child: Builder(builder: (context) {
final palette = context.watch<Palette>();
return MaterialApp.router(
title: 'Flutter Demo',
theme: ThemeData.from(
colorScheme: ColorScheme.fromSeed(
seedColor: palette.darkPen,
background: palette.backgroundMain,
),
textTheme: TextTheme(
bodyMedium: TextStyle(
color: palette.ink,
),
),
useMaterial3: true,
),
routeInformationProvider: _router.routeInformationProvider,
routeInformationParser: _router.routeInformationParser,
routerDelegate: _router.routerDelegate,
scaffoldMessengerKey: scaffoldMessengerKey,
);
}),
),
);
}
}