如何编辑Flutter深色模式 [英] How can I edit Flutter dark mode

查看:140
本文介绍了如何编辑Flutter深色模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对代码实施了暗模式。

I implemented dark mode to my code.

应用程序以true模式打开。

The application opens in light mode true.

我的主代码

void main() async {
  runApp(
    ChangeNotifierProvider(
      builder: (_) => ThemeProvider(isLightTheme: true),
      child: MyApp(),
    ),
  );
}

在这里,用户更改主题,并使用sharedpereferences保存当前设置。

From here, the user changes the theme and I save the current setting with sharedpereferences.

class ThemeProvider with ChangeNotifier {
  bool isLightTheme;
  ThemeProvider({this.isLightTheme});

  ThemeData get getThemeData => isLightTheme ? lightTheme : darkTheme;


  addStringToSF(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('boolValue', value);
    return prefs.getBool('boolValue');
  }

  set setThemeData(bool val) {
    if (val) {
      isLightTheme = true;
    } else {
      isLightTheme = false;
    }
    addStringToSF(isLightTheme);
    notifyListeners();
  }
}

我希望使用我的sharedpreferences数据中的值打开应用程序。我该怎么做。

I want the application to be opened with the value in my sharedpreferences data. How can I do that.

推荐答案

在您的 main 函数上,您可以获取 SharedPreferences 实例并查找所需的布尔值:

On your main function you can obtain the SharedPreferences instance and look for the desired bool value:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool storedValue = prefs.getBool('boolValue');
  runApp(
    ChangeNotifierProvider(
      builder: (_) => ThemeProvider(isLightTheme: storedValue),
      child: MyApp(),
    ),
  );
}

别忘了将SharedPreferences导入到主文件的顶部:

Don't forget to import your SharedPreferences on top of the main file:

import'package:shared_preferences / shared_preferences.dart';

别忘了,因为您正在使用您必须使用的异步主要功能,然后在 runApp()之前使用确保初始化方法调用:

Don't forget that since you are using an async main function you have to use the Ensure Initialized method before the "runApp()" call:

WidgetsFlutterBinding.ensureInitialized();

这篇关于如何编辑Flutter深色模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆