init method
Initialize the theme manager.
This should be called during app startup after registerThemes. Handles migration from shared_preferences and loads saved theme.
Implementation
Future<void> init() async {
if (_isInitialized) return;
// Add observer for system brightness changes
WidgetsBinding.instance.addObserver(this);
// Load saved preferences concurrently (each is a platform-channel call)
final (
String? savedThemeId,
bool? savedFollowSystem,
String? savedPreferredLight,
String? savedPreferredDark,
) = await (
_storage.readThemeId(),
_storage.readFollowSystem(),
_storage.readPreferredLightThemeId(),
_storage.readPreferredDarkThemeId(),
).wait;
// Load preferred themes
_preferredLightThemeId = savedPreferredLight;
_preferredDarkThemeId = savedPreferredDark;
// Determine if this is first launch (no saved preferences)
final bool isFirstLaunch =
savedThemeId == null && savedFollowSystem == null;
if (savedFollowSystem != null) {
_followSystemTheme = savedFollowSystem;
}
if (savedThemeId != null && savedThemeId.isNotEmpty) {
// Use saved theme if it exists in registered themes
final bool themeExists = _themes.any((t) => t.id == savedThemeId);
if (themeExists) {
_setThemeInternal(savedThemeId, notify: true, persist: false);
}
} else if (isFirstLaunch && _initialThemeId != null) {
// First launch: use initialThemeId if provided
final bool themeExists = _themes.any((t) => t.id == _initialThemeId);
if (themeExists) {
_setThemeInternal(_initialThemeId!, notify: true, persist: true);
}
} else if (_followSystemTheme) {
// Auto-detect from system brightness
_applySystemTheme(notify: true, persist: true);
}
_isInitialized = true;
}