1

我的目标是创建一个应用程序,用户可以在其中选择他喜欢的主题。我正在使用共享首选项保存用户的选择,以便在下一次应用启动时加载它。用户可以选择: - 暗模式(独立于操作系统设置) - 亮模式(独立于操作系统设置) - 系统(根据操作系统设置在暗模式和亮模式之间更改)在 BLoC 的帮助下,我几乎达到了我想要的。但问题是我需要在 Bloc 事件中传递亮度。为了获得系统(OS)亮度,我需要使用

MediaQuery.of(context).platformBrightness

但是 Bloc 在 MaterialApp 之前启动,因此 MediaQuery 不可用。当然我可以稍后传递亮度(来自 MaterialApp 的子小部件),但随后(例如,如果用户激活了暗模式)它会从亮变为暗,但对用户来说很短的时间可见(因为在 InitialState我在灯光模式下通过)。

class MyApp extends StatelessWidget {
  final RecipeRepository recipeRepository;

  MyApp({Key key, @required this.recipeRepository})
      : assert(recipeRepository != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<ThemeBloc>(create: (context) =>
        ThemeBloc(),),

      ],
      child: BlocBuilder<ThemeBloc, ThemeState>(
        builder: (context, state){

          return MaterialApp(
            theme: state.themeData,
            title: 'Flutter Weather',
            localizationsDelegates: [
              FlutterI18nDelegate(fallbackFile: 'en',),
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate
            ],
            supportedLocales: [
              const Locale("en"),
              const Locale("de"),
            ],
            home: Home(recipeRepository: recipeRepository),
          );
        },
      ),
    );
  }
}

主题区:

class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
  @override
  ThemeState get initialState =>
      ThemeState(themeData: appThemeData[AppTheme.Bright]);

  @override
  Stream<ThemeState> mapEventToState(
    ThemeEvent event,
  ) async* {
    if (event is LoadLastTheme) {
      ThemeData themeData = await _loadLastTheme(event.brightness);
      yield ThemeState(themeData: themeData);
    }
    if (event is ThemeChanged) {
      await _saveAppTheme(event.theme);
      yield ThemeState(themeData: appThemeData[event.theme]);
    }
  }

  Future<ThemeData> _loadLastTheme(Brightness brightness) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String themeString = prefs.getString(SharedPrefKeys.appThemeKey);
    print("saved theme: $themeString");
    if ((prefs.getString(SharedPrefKeys.appThemeKey) != null) &&
        themeString != "AppTheme.System") {
      switch (themeString) {
        case "AppTheme.Bright":
          {
            return appThemeData[AppTheme.Bright];
          }
          break;

        ///Selected dark mode
        case "AppTheme.Dark":
          {
            return appThemeData[AppTheme.Dark];
          }
          break;
      }
    }

    print("brightness: $brightness");
    if (brightness == Brightness.dark) {
      return appThemeData[AppTheme.Dark];
    } else {
      return appThemeData[AppTheme.Bright];
    }

  }

  Future<void> _saveAppTheme(AppTheme appTheme) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(SharedPrefKeys.appThemeKey, appTheme.toString());
  }
}
4

1 回答 1

2

如果您绝对必须这样做,您可以MediaQuery直接从低级窗口对象获取数据,如下所示:

final brightness = MediaQueryData.fromWindow(WidgetsBinding.instance.window).platformBrightness;

但是,我强烈建议您考虑,如果您需要MediaQuery从您的集团内部访问,您应该将您BlocProvider的实例移动到您之后,MaterialApp以便您可以MediaQuery正常访问。

于 2020-02-23T17:38:09.900 回答