dart 具有共享偏好和提供商的黑暗模式Flutter

ryhaxcpt  于 2023-02-27  发布在  Flutter
关注(0)|答案(2)|浏览(139)

我想从设置页面实现暗/亮模式,其中使用了切换开关,一切正常,除了当我选择亮模式并重新启动应用程序,然后应用程序恢复到暗模式。我做错了什么?

主省道

return MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (context) => ThemeProvider()),
  ],
  child: Builder(builder: (BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Unit Converter',
      home: const HomePage(),
      themeMode: themeProvider.themeMode,
      theme: MyThemes.lightTheme,
      darkTheme: MyThemes.darkTheme,
    );
  }),
);

主题提供程序.dart

class ThemeProvider extends ChangeNotifier {
  ThemeMode themeMode = ThemeMode.dark;

  bool get isDarkMode => themeMode == ThemeMode.dark;

  void toggleTheme(bool isOn) {
    themeMode = isOn ? ThemeMode.dark : ThemeMode.light;
    notifyListeners();
  }
}

设置_页面.dart

final themeProvider = Provider.of<ThemeProvider>(context);

SwitchListTile(
title: const Text('Dark Mode'),
                  value: themeProvider.isDarkMode,
                  onChanged: (value) {
                    final provider =
                    Provider.of<ThemeProvider>(context, listen: false);
                    provider.toggleTheme(value);
                  },
                ),
tpgth1q7

tpgth1q71#

这是因为,您尚未将用户选择的主题存储在本地共享偏好设置/其他数据库中。要执行您尝试执行的操作,您需要在更改主题时将用户当前选择的主题保留在共享偏好设置中,并且在打开应用时,您需要检查用户选择的主题,并相应地更新主题。为此:
像这样更新您的ThemeProvider

class ThemeProvider extends ChangeNotifier {

  ///This will get called at initial and check the theme you've currently stored. and update the theme initially.
  ThemeProvider() {
    getThemeAtInit();
  }

  
  getThemeAtInit() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    bool? isDarkTheme =
        sharedPreferences.getBool("is_dark");
    if (isDarkTheme != null && isDarkTheme!) {
      themeMode = ThemeMode.dark;
    } else {
      themeMode = ThemeMode.light;
      }
      notifyListeners();
    }

  ThemeMode themeMode = ThemeMode.dark;

  bool get isDarkMode => themeMode == ThemeMode.dark;

  void toggleTheme(bool isOn) async{
        themeMode = isOn ? ThemeMode.dark : ThemeMode.light;
        notifyListeners();
        SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
        sharedPreferences.setBool("is_dark", themeMode == ThemeMode.dark) //Update this as per your condition.
      }
}

做了这个你就可以走了。

yacmzcpb

yacmzcpb2#

您需要将当前主题保存在本地存储(共享偏好设置)中。和在应用重新启动时调用共享偏好设置中存在的主题

相关问题