如何聆听Flutter中对platformBrightness的更改?

时间:2019-10-06 19:40:12

标签: flutter themes

我正在建立一个系统,当用户将系统主题更改为暗模式时,它将更改主题,并且使用Flutter,它运行良好!但是,当用户更改系统主题时,系统导航和状态栏不会更改其颜色。我在build方法内部的主页上运行了代码,但这似乎没有做到。这是主页构建方法中的代码:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Brightness sysBrightness = MediaQuery.of(context).platformBrightness;
    if (sysBrightness == Brightness.dark)
      Themes.setDarkSystemColors();
    else
      Themes.setLightSystemColors();

    return Scaffold(
      appBar: CustomAppBar(title: "Home"),
      drawer: CustomDrawer(),
      body: SizedBox(),
    );
  }
}

以下是主应用中带有theme:darkTheme:的代码:

    return MaterialApp(
      initialRoute: '/',
      routes: routes,
      navigatorObservers: [_routeObserver],
      theme: Themes.lightTheme,
      darkTheme: Themes.darkTheme,
      debugShowCheckedModeBanner: false,
      title: 'School Life',
    );

3 个答案:

答案 0 :(得分:1)

覆盖initState方法并使用onPlatformBrightnessChanged

@override
void initState() {
  super.initState();

  final window = WidgetsBinding.instance.window;
  window.onPlatformBrightnessChanged = () {
    // This callback gets invoked every time brightness changes
    final brightness = window.platformBrightness;
  };
}

答案 1 :(得分:0)

有一个ThemeMode枚举(我认为从Flutter 1.9版本开始)。因此,您可以将theme设置为亮,将darkTheme设置为黑暗,然后themeModeThemeMode.system(默认),ThemeMode.lightThemeMode.dark)确定哪个主题将被使用。

MaterialApp(
  theme: ThemeData.light(),
  darkTheme: ThemeData.dark(),
  themeMode: ThemeMode.system,
)

但是,我不确定是否有办法侦听platformBrightness的更改(ThemeMode在后​​台也使用platformBrightness)。您将需要重建MaterialApp ...

答案 2 :(得分:0)

使用(从WidgetsBinding)收听更改

void didChangePlatformBrightness()

https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver/didChangePlatformBrightness.html