-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.dart
More file actions
433 lines (386 loc) · 13.6 KB
/
Copy pathmain.dart
File metadata and controls
433 lines (386 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'app_theme.dart';
import 'providers/providers.dart';
import 'router.dart';
import 'services/services.dart';
import 'utils/utils.dart';
import 'widgets/widgets.dart';
import 'firebase_options.dart';
import 'url_strategy_stub.dart'
if (dart.library.html) 'package:flutter_web_plugins/url_strategy.dart';
void main() async {
// coverage:ignore-start
// Configure path-based URLs for web (removes # from URLs)
if (kIsWeb) {
usePathUrlStrategy();
}
WidgetsFlutterBinding.ensureInitialized();
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Pass all uncaught Flutter errors to Crashlytics. Transient google_fonts
// font-fetch failures are downgraded to non-fatal (see
// isTransientFontLoadError).
FlutterError.onError = (details) {
final isBenign = isTransientFontLoadError(
details.exception,
details.stack,
);
if (isBenign) {
FirebaseCrashlytics.instance.recordFlutterError(details);
} else {
FirebaseCrashlytics.instance.recordFlutterFatalError(details);
}
};
// Pass all uncaught asynchronous errors to Crashlytics
PlatformDispatcher.instance.onError = (error, stack) {
final isBenign = isTransientFontLoadError(error, stack);
FirebaseCrashlytics.instance.recordError(error, stack, fatal: !isBenign);
return true;
};
// Log app launch
await AnalyticsService().logAppLaunch();
} catch (e) {
// Log to console in debug mode, but allow app to continue
debugPrint('Failed to initialize Firebase: $e');
}
runApp(const BeerFestivalApp());
// coverage:ignore-end
}
/// Whether [error] originates from `google_fonts` runtime font fetching.
///
/// google_fonts downloads fonts over HTTP on first use. When the device is
/// offline or the font CDN fails, the load throws an uncaught async error.
/// The app keeps running with a fallback font, so such failures are transient
/// and non-fatal — they must not be recorded to Crashlytics as fatal crashes,
/// which would otherwise distort the crash-free metric.
bool isTransientFontLoadError(Object error, StackTrace? stack) {
if (error.toString().contains('Failed to load font')) return true;
return stack != null && stack.toString().contains('google_fonts');
}
class BeerFestivalApp extends StatelessWidget {
const BeerFestivalApp({super.key});
@override
Widget build(BuildContext context) {
// coverage:ignore-start
return ChangeNotifierProvider(
create: (_) => BeerProvider(),
child: Builder(
builder: (context) {
final themeMode = context.watch<BeerProvider>().themeMode;
return MaterialApp.router(
title: 'Cambridge Beer Festival',
debugShowCheckedModeBanner: false,
theme: buildAppTheme(Brightness.light),
darkTheme: buildAppTheme(Brightness.dark),
themeMode: themeMode,
routerConfig: appRouter,
);
},
),
);
// coverage:ignore-end
}
}
/// Widget that initializes the BeerProvider before rendering children
/// This ensures provider is initialized for all routes, including deep links
class ProviderInitializer extends StatefulWidget {
final Widget child;
const ProviderInitializer({super.key, required this.child});
@override
State<ProviderInitializer> createState() => _ProviderInitializerState();
}
class _ProviderInitializerState extends State<ProviderInitializer>
with WidgetsBindingObserver {
bool _initialized = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
// When app resumes to foreground, refresh data if stale
if (state == AppLifecycleState.resumed) {
unawaited(context.read<BeerProvider>().refreshIfStale());
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_initialized) {
_initialized = true;
// Initialize and load drinks for all routes. initialize() never throws
// (a startup failure surfaces as provider.error), so the redirect below
// always runs and the app never strands on the loading screen.
final provider = context.read<BeerProvider>();
unawaited(
provider.initialize().then((_) {
unawaited(provider.loadDrinks());
// After initialization, trigger redirects that were deferred
_handlePostInitRedirect();
}),
);
}
}
/// Handle route redirects after provider initialization
///
/// CONTEXT: go_router's redirect callbacks run once on initial navigation and
/// don't re-run when provider state changes. This method explicitly handles
/// redirects that were deferred during initialization.
///
/// KNOWN LIMITATIONS:
/// - Deep links with invalid festival IDs in subpaths are NOT redirected
/// Example: /invalid-fest/drink/abc stays at /invalid-fest/drink/abc
/// Reason: These match route patterns directly (/:festivalId/drink/:id)
/// bypassing the festival home redirect logic
/// Impact: User sees 404 or broken state until they navigate away
/// Fix: Requires adding festival ID validation to ALL route builders
///
/// - URL fragments are not preserved during redirects
/// Example: /invalid-fest#section → /cbf2025 (loses #section)
/// Impact: Scroll position hints from deep links are lost
/// Fix: Preserve currentUri.fragment in redirect URL construction
void _handlePostInitRedirect() {
if (!mounted) return;
try {
final router = GoRouter.of(context);
final state = GoRouterState.of(context);
final provider = context.read<BeerProvider>();
final currentUri = state.uri;
final currentPath = currentUri.path;
final segments = currentUri.pathSegments;
// Check if we're on root path - redirect to festival home
if (currentPath == '/') {
router.go('/${provider.currentFestival.id}');
return;
}
// Global routes (no festival scope) - do NOT redirect these
// Uses constant from router.dart to avoid duplication
if (globalRoutes.contains(currentPath)) {
return; // Stay on global route
}
// For festival-scoped routes, validate the festival ID
// Early return: if already on valid festival route, skip expensive checks
if (segments.isNotEmpty && provider.isValidFestivalId(segments.first)) {
// Sync provider when the URL festival differs from the current one.
// This is the primary fix for cold-loading a non-default festival URL
// (browser refresh, shared link opened fresh).
if (segments.first != provider.currentFestival.id) {
final festival = provider.getFestivalById(segments.first);
if (festival != null) {
unawaited(provider.setFestival(festival, persist: false));
}
}
return;
}
// Path pattern: /:festivalId or /:festivalId/...
// Extract first path segment as potential festival ID
if (segments.isEmpty) return;
final firstSegment = segments.first;
// If first segment is not a valid festival ID, redirect
if (!provider.isValidFestivalId(firstSegment)) {
// Preserve the rest of the path and query parameters
final restOfPath = segments.length > 1
? '/${segments.sublist(1).join('/')}'
: '';
final queryString = currentUri.query.isNotEmpty
? '?${currentUri.query}'
: '';
router.go('/${provider.currentFestival.id}$restOfPath$queryString');
}
} catch (e, stackTrace) {
if (kDebugMode) {
debugPrint('Post-init redirect error: $e');
debugPrint(stackTrace.toString());
} else {
// coverage:ignore-start
// In production, log to crashlytics
final provider = context.read<BeerProvider>();
unawaited(
provider.analyticsService.logError(
e,
stackTrace,
reason: 'Post-initialization redirect failed',
),
);
// coverage:ignore-end
}
}
}
@override
Widget build(BuildContext context) {
final provider = context.watch<BeerProvider>();
// Show loading screen until provider is initialized
if (provider.isLoading && provider.allDrinks.isEmpty) {
return const Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Loading festival data...'),
],
),
),
);
}
return widget.child;
}
}
class BeerFestivalHome extends StatefulWidget {
final Widget child;
const BeerFestivalHome({super.key, required this.child});
@override
State<BeerFestivalHome> createState() => _BeerFestivalHomeState();
}
const Duration _exitConfirmationWindow = Duration(seconds: 2);
const String _exitConfirmationMessage = 'Press back again to exit';
class _BeerFestivalHomeState extends State<BeerFestivalHome> {
Timer? _exitConfirmationTimer;
int get _currentIndex {
// Try to get the current location from GoRouter
try {
final location = GoRouterState.of(context).uri.toString();
if (location.endsWith('/favorites')) return 1;
return 0;
} catch (e) {
// If GoRouter is not available (e.g., in tests), default to 0
return 0;
}
}
/// Get festivalId from current route
String? get _festivalId {
try {
final params = GoRouterState.of(context).pathParameters;
return params['festivalId'];
} catch (e) {
return null;
}
}
void _onDestinationSelected(int index) {
// Try to use GoRouter navigation
try {
// Get festival ID from URL or fall back to provider
final festivalId =
_festivalId ?? context.read<BeerProvider>().currentFestival.id;
if (index == 0) {
context.go(buildFestivalHome(festivalId));
} else if (index == 1) {
context.go(buildFavoritesPath(festivalId));
}
} catch (e) {
// If GoRouter is not available, this is a no-op
// (tests that don't use GoRouter won't navigate)
}
}
@override
void dispose() {
_exitConfirmationTimer?.cancel();
super.dispose();
}
void _handleExitConfirmation() {
if (!mounted) return;
if (_exitConfirmationTimer?.isActive ?? false) {
_exitConfirmationTimer!.cancel();
_exitConfirmationTimer = null;
if (!kIsWeb) {
SystemNavigator.pop();
}
return;
}
_exitConfirmationTimer = Timer(_exitConfirmationWindow, () {
_exitConfirmationTimer = null;
});
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(
content: Text(_exitConfirmationMessage),
duration: _exitConfirmationWindow,
),
);
}
@override
Widget build(BuildContext context) {
final hasNavigationHistory = canPopNavigation(context);
return PopScope(
canPop: kIsWeb || hasNavigationHistory,
onPopInvokedWithResult: (didPop, result) {
final canPopNow = canPopNavigation(context);
if (didPop || canPopNow) {
_exitConfirmationTimer?.cancel();
_exitConfirmationTimer = null;
return;
}
_handleExitConfirmation();
},
child: Scaffold(
body: Stack(children: [widget.child, const EnvironmentBadge()]),
bottomNavigationBar: NavigationBar(
height: 60,
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
selectedIndex: _currentIndex,
onDestinationSelected: _onDestinationSelected,
destinations: [
NavigationDestination(
key: const Key('drinks_tab'),
icon: Semantics(
label: 'Drinks tab, browse all festival drinks',
child: Opacity(
opacity: 0.6,
child: Image.asset(
'assets/app_icon.png',
width: 24,
height: 24,
),
),
),
selectedIcon: Semantics(
label: 'Drinks tab, browse all festival drinks',
child: Image.asset(
'assets/app_icon.png',
width: 24,
height: 24,
),
),
label: 'Drinks',
),
NavigationDestination(
key: const Key('favorites_tab'),
icon: Semantics(
label:
'My Festival tab, view your want-to-try list and'
' tasting log',
child: const Icon(Icons.bookmark_outline),
),
selectedIcon: Semantics(
label:
'My Festival tab, view your want-to-try list and'
' tasting log',
child: const Icon(Icons.bookmark),
),
label: 'My Festival',
),
],
),
),
);
}
}