【问题标题】:How can I edit Flutter dark mode如何编辑 Flutter 暗模式
【发布时间】:2020-11-14 14:11:40
【问题描述】:

我在我的代码中实现了暗模式。

应用程序在 light 模式下打开 true。

我的主要代码

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

从这里,用户更改主题,然后我使用 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 数据中的值打开应用程序。我该怎么做。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

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

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

    不要忘记在主文件顶部导入您的 SharedPreferences:

    import 'package:shared_preferences/shared_preferences.dart';

    不要忘记,由于您使用的是异步主函数,因此您 have to 在“runApp()”调用之前使用 Ensure Initialized 方法:

    WidgetsFlutterBinding.ensureInitialized();

    【讨论】:

    • 它给了我一个错误。 If you're running an application and need to access the binary messenger before runApp()` 已经被调用(例如,在插件初始化期间),那么你需要先显式调用WidgetsFlutterBinding.ensureInitialized()。` 然后我在第一行添加了 WidgetsFlutterBinding.ensureInitialized() 方法。
    • 新的错误。 '我/颤振(26446):══╡小部件库发现异常╞═════════════════════════␕═══════════════ ══════════════════════════ I/flutter(26446):在构建MyApp(脏,依赖项:I/flutter(26446)时引发了以下_TypeError ): [InheritedProvider]): I/flutter (26446): type 'Future' is not a subtype of type 'bool''
    • @thekavak 您需要在主函数中添加以下行:WidgetsFlutterBinding.ensureInitialized();。我编辑了我的答案以说明这一点。
    【解决方案2】:

    '如果你想根据你的系统模式在你的应用程序中使用暗/亮模式,假设终端设备支持-MaterialApp有一个theme属性,它代表' System light theme' 其中darkTheme 属性代表'系统暗模式'。我创建了一个名为 AppTheme 的类,我在其中初始化了 2 个 static final ThemeData 对象:

    class AppTheme {
      static final ThemeData lightTeme = ThemeData(
          //Theme light
          brightness: Brightness.light,
          primaryColor: Colors.white,
          accentColor: Colors.black,
          inputDecorationTheme: InputDecorationTheme(
              labelStyle: TextStyle(color: Colors.black),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25.0),
                  borderSide: BorderSide(color: Colors.black)),
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25.0),
                  borderSide: BorderSide(color: Colors.black))),
          buttonTheme: ButtonThemeData(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(18.0),
                side: BorderSide(color: Colors.black)),
          ),
          // This makes the visual density adapt to the platform that you run
          // the app on. For desktop platforms, the controls will be smaller and
          // closer together (more dense) than on mobile platforms.
          visualDensity: VisualDensity.adaptivePlatformDensity);
    
      static final ThemeData darkTheme = ThemeData(
          brightness: Brightness.dark,
          primaryColor: Colors.black,
          accentColor: Colors.white,
          inputDecorationTheme: InputDecorationTheme(
              labelStyle: TextStyle(color: Colors.white),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25.0),
                  borderSide: BorderSide(color: Colors.white)),
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25.0),
                  borderSide: BorderSide(color: Colors.white))),
          buttonTheme: ButtonThemeData(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(18.0),
                side: BorderSide(color: Colors.white)),
          ),
          
          //Button Theme Light
          visualDensity: VisualDensity.adaptivePlatformDensity);
    }
    

    您可以在 MaterialApp 小部件中访问它们:

    @override
      Widget build(BuildContext context) {
        return MaterialApp(
          localizationsDelegates: [
            S.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate
          ],
          supportedLocales: S.delegate.supportedLocales,
          theme: AppTheme.lightTeme,
          darkTheme: AppTheme.darkTheme,
          home: HomeworkDiaryApp(),
        );
      }
    

    您不必担心您的应用程序处理更改。一旦您更改系统暗模式,它会自动执行(在我的真实设备上测试三星 Galaxy s8 就像一个魅力)

    我认为,当人们今天最常使用的所有手机都具有系统暗模式或亮模式时,实施“仅在应用中的暗模式和亮模式”是自相矛盾的!

    【讨论】:

    • 谢谢。我想手动控制,我可以做到这一点,但我不能从选定的功能亮或暗开始
    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2018-02-02
    • 2020-11-06
    相关资源
    最近更新 更多