Flutter 亮暗模式未更新提供程序

jfgube3f  于 2023-01-31  发布在  Flutter
关注(0)|答案(2)|浏览(147)

我有一个控制器的主题变化像这样

class ThemeProvider extends ChangeNotifier {
  ThemeMode systemThemeMode = preferences.getBool(Keys.isDarkMode) == null
      ? ThemeMode.light
      : preferences.getBool(Keys.isDarkMode) == true
          ? ThemeMode.dark
          : ThemeMode.light;

  bool isDarkMode =
      SchedulerBinding.instance.window.platformBrightness.name == "dark"
          ? true
          : false;

  toggleTheme(bool isPro) {
    if (isPro) {
      isDarkMode = !isDarkMode;
      preferences.setBool(Keys.isDarkMode, isDarkMode);
      systemThemeMode = isDarkMode ? ThemeMode.dark : ThemeMode.light;
      notifyListeners();
    }
  }
}

而这是我的主要。 dart

return MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (context) => UserController()),
      ChangeNotifierProvider(create: (context) => TeamsController()),
      ChangeNotifierProvider(create: (context) => MatchListController()),
      ChangeNotifierProvider(create: (context) => NewsProvider()),
      ChangeNotifierProvider(create: (context) => ThemeProvider()),
    ],
    builder: (context, _) {
      final themeProvider =
          Provider.of<ThemeProvider>(context, listen: false);
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: LightDarkTheme.lightTheme,
        darkTheme: LightDarkTheme.darkTheme,
        title: 'CricketR Plus',
        themeMode: themeProvider.systemThemeMode,
        home: LoginScreen(),
      );
    });

我正在通过toggleTheme更新值,我可以看到它通过打印更新,但主题将从亮到暗。但如果我切换并重新启动我的应用程序,那么它的工作非常好。

w8f9ii69

w8f9ii691#

使用Provider.of<ThemeProvider>(context, listen: false)可以指定不想侦听提供程序中的更改。
相反,当在MaterialApp内设置themeMode时,请使用此函数:

themeMode: context.watch<ThemeProvider>().systemThemeMode,
dtcbnfnu

dtcbnfnu2#

您需要使用Consumer widget来 Package 您的MaterialApp。然后,您可以在Consumer中调用ThemeProvider,并在主题切换时更新MaterialApp的themeMode。
下面是一个例子

return MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (context) => UserController()),
      ChangeNotifierProvider(create: (context) => TeamsController()),
      ChangeNotifierProvider(create: (context) => MatchListController()),
      ChangeNotifierProvider(create: (context) => NewsProvider()),
      ChangeNotifierProvider(create: (context) => ThemeProvider()),
    ],
    builder: (context, _) {
      return Consumer<ThemeProvider>(
        builder: (context, themeProvider, child) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            theme: LightDarkTheme.lightTheme,
            darkTheme: LightDarkTheme.darkTheme,
            title: 'CricketR Plus',
            themeMode: themeProvider.systemThemeMode,
            home: LoginScreen(),
          );
        },
      );
    });

相关问题