flutter 使用简单provider

flutter使用provider,实现页面白天和夜晚模式的切换

第一步:pub.dev中获取provider

地址:https://pub.dev/packages/provider

第二步:定义ChangeNotifierProvider:

List topProviders = [
  ChangeNotifierProvider(create: (_) => ThemeProvider())
];

第三步:编写ThemeProvider:

extension ThemeModeExtension on ThemeMode {
  String get value => ['System', 'Light', 'Dark'][index];
}

class ThemeProvider extends ChangeNotifier {
  ThemeMode _themeMode;
  var _platformBrightness = SchedulerBinding.instance.window.platformBrightness;

  ///系统dark mode发生变化
  void darkModeChange() {
    if (_platformBrightness !=
        SchedulerBinding.instance.window.platformBrightness) {
      _platformBrightness = SchedulerBinding.instance.window.platformBrightness;
      notifyListeners();
    }
  }

  ///是否是dark mode
  bool isDark() {
    if (_themeMode == ThemeMode.system) {
      //获取系统的Dark Mode
      return SchedulerBinding.instance.window.platformBrightness ==
          Brightness.dark;
    }
    return _themeMode == ThemeMode.dark;
  }

  ///获取主题模式
  ThemeMode getThemeMode() {
    String theme = HiCache.getInstance().get(HiConstants.theme);
    switch (theme) {
      case 'Dark':
        _themeMode = ThemeMode.dark;
        break;
      case 'System':
        _themeMode = ThemeMode.system;
        break;
      default:
        _themeMode = ThemeMode.light;
        break;
    }
    return _themeMode;
  }

  ///设置主题
  void setTheme(ThemeMode themeMode) {
    HiCache.getInstance().setString(HiConstants.theme, themeMode.value);
    notifyListeners();
  }

  ///获取主题
  ThemeData getTheme({bool isDarkMode = false}) {
    var themeData = ThemeData(
      brightness: isDarkMode ? Brightness.dark : Brightness.light,
      errorColor: isDarkMode ? HiColor.dark_red : HiColor.red,
      primaryColor: isDarkMode ? HiColor.dark_bg : white,
      accentColor: isDarkMode ? primary[50] : white,
      //tab指示器
      indicatorColor: isDarkMode ? primary[50] : white,
      //页面背景色
      scaffoldBackgroundColor: isDarkMode ? HiColor.dark_bg : white,
    );
    return themeData;
  }
}

第四步:main页面使用provider:

return MultiProvider(
            providers: topProviders,
            child: Consumer(
              builder: (BuildContext context, ThemeProvider themeProvider,
                  Widget child) {
                return MaterialApp(
                  home: widget,
                  theme: themeProvider.getTheme(),
                  darkTheme: themeProvider.getTheme(isDarkMode: true),
                  themeMode: themeProvider.getThemeMode(),
                );
              },
            ),
          );

第五步:普通页面使用provider:

var themeProvider = context.watch();
    if (themeProvider.isDark()) {
      statusStyle = StatusStyle.LIGHT_CONTENT;
    }

你可能感兴趣的:(flutter,dart,混合开发,flutter)