kdsuneraavinash / theme_provider

Easy to use, customizable and pluggable Theme Provider.
https://pub.dartlang.org/packages/theme_provider
MIT License
152 stars 28 forks source link

onInitCallback called every time app moved to the background and back #17

Open narritt opened 3 years ago

narritt commented 3 years ago

Seems like onInitCallback called every time when the application moved to the background and back. Every time there is an animation of changing theme from light to dark.

My build method:

return ThemeProvider(
      saveThemesOnChange: true,
      themes: [
        AppTheme(
          id: 'light',
          description: 'Light',
          data: _theme
        ),
        AppTheme(
          id: 'dark',
          description: 'Dark',
          data: _themeDark
        ),
      ],
      onInitCallback: _onThemesInitCallback,
      child: ThemeConsumer(
        child: Builder(
          builder: (themeContext) => MaterialApp(
              ...
          ),
        ),
      ),
    );

And _onThemesInitCallback method:

  void _onThemesInitCallback(ThemeController controller, previouslySavedThemeFuture) async {
    print("_onThemesInitCallback ${controller.currentThemeId}");
    String? savedTheme = await previouslySavedThemeFuture;
    print("savedTheme $savedTheme");
    if (savedTheme != null) {
      controller.setTheme(savedTheme);
    } else {
      // If previous theme not found, use platform default
      Brightness platformBrightness = SchedulerBinding.instance!.window.platformBrightness;
      if (platformBrightness == Brightness.dark) {
        controller.setTheme('dark');
      } else {
        controller.setTheme('light');
      }
      // Forget the saved theme(which were saved just now by previous lines)
      controller.forgetSavedTheme();
    }
    print("_onThemesInitCallback END ${controller.currentThemeId}");
  }

Also, I have prints on the application moved to the background and foreground (AppLifecycleState.resumed and .paused) What I see in the logs during the test on the video:

I/flutter ( 5434): Application is on the foreground
I/flutter ( 5434): _onThemesInitCallback light
I/flutter ( 5434): savedTheme dark
I/flutter ( 5434): _onThemesInitCallback END dark
I/flutter ( 5434): _onThemesInitCallback light
I/flutter ( 5434): savedTheme dark
I/flutter ( 5434): _onThemesInitCallback END dark
I/flutter ( 5434): Application is on the background
I/flutter ( 5434): _onThemesInitCallback light
I/flutter ( 5434): savedTheme dark
I/flutter ( 5434): _onThemesInitCallback END dark

Video: https://youtu.be/79vcS8sgYys

Tried to fix it by myself in my application, but seems like something strange in the package. Thanks a lot for the package and your awesome work!

palorotolo commented 3 years ago

me too.

kdsuneraavinash commented 3 years ago

The onInitCallback is simply called whenever ThemeController is initialized. Can you check with the example app to check if the issue is still there?