initializeTheme method

Future<void> initializeTheme()

Initializes the theme by checking if the app is running for the first time.

If the app is running for the first time, it sets the theme to the system theme and persists the chosen theme to SharedPreferences.

If the app is not running for the first time, it retrieves the previously chosen theme from SharedPreferences and sets the theme accordingly.

If the previously chosen theme was set to the system theme, it checks the current platform brightness and sets the theme accordingly.

Emits a new ThemeState with the chosen isDark and ThemeMode.

Implementation

Future<void> initializeTheme() async {
  final isFirstRun = await _themeSharedPreferences.isFirstRun();

  if (isFirstRun == null || isFirstRun) {
    await setSystemTheme();
    await _themeSharedPreferences.setFirstRun(value: false);
  } else {
    final isDark = await _themeSharedPreferences.getTheme();
    final savedMode = await _themeSharedPreferences.getThemeMode();

    if (savedMode == ThemeMode.system) {
      final platformBrightness =
          PlatformDispatcher.instance.platformBrightness;
      final newIsDark = platformBrightness == Brightness.dark;
      final newState = state.copyWith(
        isDark: newIsDark,
        themeMode: ThemeMode.system,
      );
      await _persistTheme(newState);
      emit(newState);
    } else {
      emit(state.copyWith(isDark: isDark, themeMode: savedMode));
    }
  }
}