refactor: app startup improvements
This commit is contained in:
259
lib/main.dart
259
lib/main.dart
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
import 'dart:developer' as developer;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
@@ -8,48 +10,87 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'core/providers/app_providers.dart';
|
||||
import 'core/router/app_router.dart';
|
||||
import 'shared/theme/app_theme.dart';
|
||||
import 'shared/theme/theme_extensions.dart';
|
||||
import 'shared/widgets/offline_indicator.dart';
|
||||
import 'features/auth/providers/unified_auth_providers.dart';
|
||||
import 'core/auth/auth_state_manager.dart';
|
||||
import 'core/utils/debug_logger.dart';
|
||||
import 'core/utils/system_ui_style.dart';
|
||||
|
||||
import 'package:conduit/l10n/app_localizations.dart';
|
||||
import 'core/services/share_receiver_service.dart';
|
||||
import 'core/providers/app_startup_providers.dart';
|
||||
import 'core/models/server_config.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
developer.TimelineTask? _startupTimeline;
|
||||
|
||||
// Enable edge-to-edge globally (back-compat on pre-Android 15)
|
||||
// Pairs with Activity's EdgeToEdge.enable and our SafeArea usage.
|
||||
// Do not block first frame on system UI mode; apply shortly after startup
|
||||
// ignore: discarded_futures
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
void main() {
|
||||
runZonedGuarded(
|
||||
() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
const secureStorage = FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(
|
||||
encryptedSharedPreferences: true,
|
||||
sharedPreferencesName: 'conduit_secure_prefs',
|
||||
preferencesKeyPrefix: 'conduit_',
|
||||
resetOnError: false,
|
||||
),
|
||||
iOptions: IOSOptions(
|
||||
accountName: 'conduit_secure_storage',
|
||||
synchronizable: false,
|
||||
),
|
||||
);
|
||||
// Global error handlers
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
DebugLogger.error('Flutter error', details.exception);
|
||||
final stack = details.stack;
|
||||
if (stack != null) {
|
||||
debugPrint(stack.toString());
|
||||
}
|
||||
};
|
||||
WidgetsBinding.instance.platformDispatcher.onError = (error, stack) {
|
||||
DebugLogger.error('Uncaught platform error', error);
|
||||
debugPrint(stack.toString());
|
||||
return true;
|
||||
};
|
||||
|
||||
runApp(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
sharedPreferencesProvider.overrideWithValue(sharedPrefs),
|
||||
secureStorageProvider.overrideWithValue(secureStorage),
|
||||
],
|
||||
child: const ConduitApp(),
|
||||
),
|
||||
// Start startup timeline instrumentation
|
||||
_startupTimeline = developer.TimelineTask();
|
||||
_startupTimeline!.start('app_startup');
|
||||
_startupTimeline!.instant('bindings_initialized');
|
||||
|
||||
// Enable edge-to-edge globally (back-compat on pre-Android 15)
|
||||
// Pairs with Activity's EdgeToEdge.enable and our SafeArea usage.
|
||||
// Do not block first frame on system UI mode; apply shortly after startup
|
||||
// ignore: discarded_futures
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
_startupTimeline!.instant('edge_to_edge_enabled');
|
||||
|
||||
final sharedPrefs = await SharedPreferences.getInstance();
|
||||
_startupTimeline!.instant('shared_prefs_ready');
|
||||
const secureStorage = FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(
|
||||
encryptedSharedPreferences: true,
|
||||
sharedPreferencesName: 'conduit_secure_prefs',
|
||||
preferencesKeyPrefix: 'conduit_',
|
||||
resetOnError: false,
|
||||
),
|
||||
iOptions: IOSOptions(
|
||||
accountName: 'conduit_secure_storage',
|
||||
synchronizable: false,
|
||||
),
|
||||
);
|
||||
_startupTimeline!.instant('secure_storage_ready');
|
||||
|
||||
// Finish timeline after first frame paints
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_startupTimeline?.instant('first_frame_rendered');
|
||||
_startupTimeline?.finish();
|
||||
_startupTimeline = null;
|
||||
});
|
||||
|
||||
runApp(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
sharedPreferencesProvider.overrideWithValue(sharedPrefs),
|
||||
secureStorageProvider.overrideWithValue(secureStorage),
|
||||
],
|
||||
child: const ConduitApp(),
|
||||
),
|
||||
);
|
||||
developer.Timeline.instantSync('runApp_called');
|
||||
},
|
||||
(error, stack) {
|
||||
DebugLogger.error('Uncaught zone error', error);
|
||||
debugPrint(stack.toString());
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,42 +102,19 @@ class ConduitApp extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _ConduitAppState extends ConsumerState<ConduitApp> {
|
||||
bool _attemptedSilentAutoLogin = false;
|
||||
ProviderSubscription<AuthNavigationState>? _authNavSubscription;
|
||||
ProviderSubscription<AsyncValue<ServerConfig?>>? _activeServerSubscription;
|
||||
ProviderSubscription<void>? _startupFlowSubscription;
|
||||
Brightness? _lastAppliedOverlayBrightness;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Defer heavy provider initialization to after first frame to render UI sooner
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _initializeAppState());
|
||||
|
||||
_authNavSubscription = ref.listenManual<AuthNavigationState>(
|
||||
authNavigationStateProvider,
|
||||
(previous, next) {
|
||||
if (next == AuthNavigationState.needsLogin) {
|
||||
_maybeAttemptSilentLogin();
|
||||
} else {
|
||||
_attemptedSilentAutoLogin = false;
|
||||
}
|
||||
},
|
||||
// Activate app startup flow without tying it to root widget rebuilds
|
||||
_startupFlowSubscription = ref.listenManual<void>(
|
||||
appStartupFlowProvider,
|
||||
(previous, next) {},
|
||||
);
|
||||
|
||||
_activeServerSubscription = ref.listenManual<AsyncValue<ServerConfig?>>(
|
||||
activeServerProvider,
|
||||
(previous, next) {
|
||||
next.when(
|
||||
data: (server) {
|
||||
if (server != null) {
|
||||
_maybeAttemptSilentLogin();
|
||||
}
|
||||
},
|
||||
loading: () {},
|
||||
error: (error, stackTrace) {},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
Future.microtask(_maybeAttemptSilentLogin);
|
||||
}
|
||||
|
||||
void _initializeAppState() {
|
||||
@@ -110,98 +128,59 @@ class _ConduitAppState extends ConsumerState<ConduitApp> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_authNavSubscription?.close();
|
||||
_activeServerSubscription?.close();
|
||||
_startupFlowSubscription?.close();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _maybeAttemptSilentLogin() {
|
||||
if (_attemptedSilentAutoLogin) return;
|
||||
|
||||
final authState = ref.read(authNavigationStateProvider);
|
||||
if (authState != AuthNavigationState.needsLogin) {
|
||||
return;
|
||||
}
|
||||
|
||||
final activeServerAsync = ref.read(activeServerProvider);
|
||||
final hasActiveServer = activeServerAsync.maybeWhen(
|
||||
data: (server) => server != null,
|
||||
orElse: () => false,
|
||||
);
|
||||
|
||||
if (!hasActiveServer) {
|
||||
return;
|
||||
}
|
||||
|
||||
_attemptedSilentAutoLogin = true;
|
||||
|
||||
Future.microtask(() async {
|
||||
try {
|
||||
final hasCreds = await ref.read(hasSavedCredentialsProvider2.future);
|
||||
if (hasCreds) {
|
||||
await ref.read(authActionsProvider).silentLogin();
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignore silent login errors; fall back to manual login.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final themeMode = ref.watch(themeModeProvider.select((mode) => mode));
|
||||
final router = ref.watch(goRouterProvider);
|
||||
ref.watch(appStartupFlowProvider);
|
||||
|
||||
final currentTheme = themeMode == ThemeMode.dark
|
||||
? AppTheme.conduitDarkTheme
|
||||
: themeMode == ThemeMode.light
|
||||
? AppTheme.conduitLightTheme
|
||||
: MediaQuery.platformBrightnessOf(context) == Brightness.dark
|
||||
? AppTheme.conduitDarkTheme
|
||||
: AppTheme.conduitLightTheme;
|
||||
|
||||
final locale = ref.watch(localeProvider);
|
||||
|
||||
return AnimatedThemeWrapper(
|
||||
theme: currentTheme,
|
||||
duration: AnimationDuration.medium,
|
||||
child: ErrorBoundary(
|
||||
child: MaterialApp.router(
|
||||
routerConfig: router,
|
||||
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
|
||||
theme: AppTheme.conduitLightTheme,
|
||||
darkTheme: AppTheme.conduitDarkTheme,
|
||||
themeMode: themeMode,
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localeListResolutionCallback: (deviceLocales, supported) {
|
||||
if (locale != null) return locale;
|
||||
if (deviceLocales == null || deviceLocales.isEmpty) {
|
||||
return supported.first;
|
||||
}
|
||||
for (final device in deviceLocales) {
|
||||
for (final loc in supported) {
|
||||
if (loc.languageCode == device.languageCode) return loc;
|
||||
}
|
||||
}
|
||||
return ErrorBoundary(
|
||||
child: MaterialApp.router(
|
||||
routerConfig: router,
|
||||
onGenerateTitle: (context) => AppLocalizations.of(context)!.appTitle,
|
||||
theme: AppTheme.conduitLightTheme,
|
||||
darkTheme: AppTheme.conduitDarkTheme,
|
||||
themeMode: themeMode,
|
||||
debugShowCheckedModeBanner: false,
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localeListResolutionCallback: (deviceLocales, supported) {
|
||||
if (locale != null) return locale;
|
||||
if (deviceLocales == null || deviceLocales.isEmpty) {
|
||||
return supported.first;
|
||||
},
|
||||
builder: (context, child) {
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
return MediaQuery(
|
||||
data: mediaQuery.copyWith(
|
||||
textScaler: mediaQuery.textScaler.clamp(
|
||||
minScaleFactor: 1.0,
|
||||
maxScaleFactor: 3.0,
|
||||
),
|
||||
}
|
||||
for (final device in deviceLocales) {
|
||||
for (final loc in supported) {
|
||||
if (loc.languageCode == device.languageCode) return loc;
|
||||
}
|
||||
}
|
||||
return supported.first;
|
||||
},
|
||||
builder: (context, child) {
|
||||
final brightness = Theme.of(context).brightness;
|
||||
if (_lastAppliedOverlayBrightness != brightness) {
|
||||
_lastAppliedOverlayBrightness = brightness;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
applySystemUiOverlayStyleOnce(brightness: brightness);
|
||||
});
|
||||
}
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
return MediaQuery(
|
||||
data: mediaQuery.copyWith(
|
||||
textScaler: mediaQuery.textScaler.clamp(
|
||||
minScaleFactor: 1.0,
|
||||
maxScaleFactor: 3.0,
|
||||
),
|
||||
child: OfflineIndicator(child: child ?? const SizedBox.shrink()),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
child: OfflineIndicator(child: child ?? const SizedBox.shrink()),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user