简体   繁体   English

Flutter:使用 Getx 持久化主题

[英]Flutter: Persisting theme using Getx

I have the following example to change from dark to light mode using Getx.我有以下示例使用 Getx 从暗模式更改为亮模式。 How i can make it Persisting?我怎样才能让它持久化? Can i use Getx to make it Persisting or need i to use another method.我可以使用 Getx 使其持久化还是需要我使用另一种方法。 I tried already, but without success.我已经尝试过了,但没有成功。


class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Get.put(ThemeController());
    return Scaffold(
      appBar: AppBar(
        title: Text('Change Theme'),
        actions: [
          GetBuilder<ThemeController>(
              builder: (controller) => IconButton(
                  icon: Icon(
                    controller.isDarkMode ? Icons.light_mode : Icons.dark_mode,
                  ),
                  onPressed: () {
                    controller.toggleDarkMode();
                  }))
        ],
      ),
    );
  }
}

class ThemeController extends GetxController {
  bool isDarkMode = false;

  void toggleDarkMode() {
    isDarkMode = !isDarkMode;
    if (isDarkMode) {
      Get.changeTheme(themeDataDark);
    } else {
      Get.changeTheme(themeDataLight);
    }
    update();
  }
}

final ThemeData themeDataLight = new ThemeData(
    brightness: Brightness.light,
    primaryColor: Colors.orange[500],
    primaryColorBrightness: Brightness.light,
    scaffoldBackgroundColor: Colors.grey[200],

final ThemeData themeDataDark = ThemeData(
  brightness: Brightness.dark,
  primaryColor: Colors.orange[700],
  primaryColorBrightness: Brightness.dark,
  scaffoldBackgroundColor: Colors.grey[850],

);

Thanks in advance for the help.在此先感谢您的帮助。

Using Getx get_storage package you can save the theme使用Getx get_storage包可以保存主题

Here is a sample code to save and retrieve the theme mode这是保存和检索主题模式的示例代码

class ThemeHelper {
  final _box = GetStorage();
  final _key = 'isDarkMode';

  /// Get isDarkMode info from local storage and return ThemeMode
  ThemeMode get theme => _loadThemeFromBox() ? ThemeMode.dark : ThemeMode.light;

  /// Load isDarkMode from local storage and if it's empty, returns false (that means default theme is light)
  bool _loadThemeFromBox() => _box.read(_key) ?? false;

  /// Save isDarkMode to local storage
  _saveThemeToBox(bool isDarkMode) => _box.write(_key, isDarkMode);

  /// Switch theme and save to local storage
  void switchTheme() {
    Get.changeThemeMode(_loadThemeFromBox() ? ThemeMode.light : ThemeMode.dark);
    _saveThemeToBox(!_loadThemeFromBox());
  }
}

and inside your main.dart just call在你的main.dart调用

 MaterialApp(
      ...
      ...
      themeMode: ThemeHelper().theme,
     
    )

To update the theme call ThemeHelper().switchTheme()更新主题调用ThemeHelper().switchTheme()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM