如何在Flutter中设置主题的SharedPreferences?

时间:2020-05-07 11:07:02

标签: flutter dart sharedpreferences flutter-layout flutter-dependencies

我在theme中添加了flutter app功能。我简要解释一下,创建了一个名为AppStyleModeNotifier的类。在此类中,我为lightdark theme设置了两种方法。我上了这个课。

import 'package:flutter/material.dart';

class AppStyleModeNotifier extends ChangeNotifier {
  int mode = 0; //0 for light and 1 for dark

  Color backgroungColor = Colors.grey[100];
  Color cardBackgroundColor = Colors.white;
  Color headlineColor = Colors.black;
  Color descriptionColor = Colors.grey[800];
  Color contentColor = Colors.grey[800];
  Color dateColor = Colors.grey[800];
  Color appbarIconColor = Colors.black;
  Color appbarBackgroundColor = Colors.white;
  Color actionButtonColor = Colors.black;
  Color appbarTextColor = Colors.black;

  switchMode() {
    if (mode == 0) {
      //if it is light mode currently switch to dark
      backgroungColor = Color(0xfff2f2f2);
      cardBackgroundColor = Colors.white;
      headlineColor = Colors.black;
      descriptionColor = Colors.grey[800];
      contentColor = Colors.grey[800];
      dateColor = Colors.grey[800];
      appbarIconColor = Colors.black;
      appbarBackgroundColor = Colors.white;
      actionButtonColor = Colors.black;
      appbarTextColor = Colors.black;
      mode = 1;
    } else {
      //if it is dark mode currently switch to light
      backgroungColor = Colors.black;
      cardBackgroundColor = Color(0xff2b2a2a);
      headlineColor = Colors.white;
      descriptionColor = Colors.white60;
      contentColor = Colors.white60;
      dateColor = Colors.white60;
      appbarIconColor = Colors.white;
      appbarBackgroundColor = Colors.black;
      actionButtonColor = Colors.white;
      appbarTextColor = Colors.white;
      mode = 0;
    }

    notifyListeners();
  }
}

现在,我在浅色和深色主题的应用程序中使用此类作为

 final appStyleMode = Provider.of<AppStyleModeNotifier>(context);

当用户单击按钮时,我使用此方法更改主题。

IconButton(
   icon: Icon(Icons.brightness_6),
   onPressed: () {
      appStyleMode.switchMode();
   }
)

但是现在我面临的问题是,当我重新启动应用程序时,它被设置为应用程序中的默认灯光主题。因此,我想设置用户关闭应用程序时由用户设置的主题。这意味着,如果用户设置了浅色主题,则当用户重新打开应用程序时,它将设置为浅色主题,而用户将其设置为深色主题,则将其设置为深色主题。如何完成此功能?

0 个答案:

没有答案