flutter进入深色模式时改变系统导航和状态栏的颜色

Change color of system navigation and status bar when entering the dark mode in flutter

我想在进入深色模式时更改系统导航和状态栏的颜色

这是我的代码:

void main() async {
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
  statusBarBrightness: Brightness.dark,
  statusBarColor: Colors.white,
  statusBarIconBrightness: Brightness.dark,
  systemNavigationBarColor: Colors.white,
  systemNavigationBarDividerColor: Colors.white,
  systemNavigationBarIconBrightness: Brightness.dark,
),
);
...
}

我使用 SystemChrome,它运行良好。但是我的问题是,我只能通过代码更改颜色手册,不能在切换到深色或浅色模式或使用系统设置时更改。

您可以像这样更改主题。

MaterialApp(
    themeMode: ThemeMode.light, // Change it as you want
    theme: ThemeData(
        primaryColor: Colors.white,
        primaryColorBrightness: Brightness.light,
        brightness: Brightness.light,
        primaryColorDark: Colors.black,
        canvasColor: Colors.white,
        // next line is important!
        appBarTheme: AppBarTheme(brightness: Brightness.light)),
    darkTheme: ThemeData(
        primaryColor: Colors.black,
        primaryColorBrightness: Brightness.dark,
        primaryColorLight: Colors.black,
        brightness: Brightness.dark,
        primaryColorDark: Colors.black,      
        indicatorColor: Colors.white,
        canvasColor: Colors.black,
        // next line is important!
        appBarTheme: AppBarTheme(brightness: Brightness.dark)),
...

在尝试了很多事情之后,我找到了以下解决问题的方法。我不知道这是否是最干净的解决方案,但它确实有效。对于那些不像我这样使用 AppBar 的人来说,这个解决方案很有趣。

技巧如下...

@override
Widget build(BuildContext context) {
 Theme.of(context).scaffoldBackgroundColor == Colors.white
    ? _lightStatusAndNavigationBar()
    : _darkStatusAndNavigationBar();
return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
...
}

查询在我的 class 的构建中,其中有我的应用程序的 NavigationBar。所有其他屏幕都连接到那里。

使用Theme.of(context).scaffoldBackgroundColor,请问状态栏和导航栏应该使用哪种设计

这是针对不同颜色的两个函数:

void _darkStatusAndNavigationBar() {
SystemChrome.setSystemUIOverlayStyle(
  SystemUiOverlayStyle(
    statusBarBrightness: Brightness.light,
    statusBarColor: Colors.grey.shade900,
    statusBarIconBrightness: Brightness.light,
    systemNavigationBarColor: Colors.grey.shade900,
    systemNavigationBarDividerColor: Colors.grey.shade900,
    systemNavigationBarIconBrightness: Brightness.light,
  ),
);
}

 void _lightStatusAndNavigationBar() {
SystemChrome.setSystemUIOverlayStyle(
  SystemUiOverlayStyle(
    statusBarBrightness: Brightness.dark,
    statusBarColor: Colors.white,
    statusBarIconBrightness: Brightness.dark,
    systemNavigationBarColor: Colors.white,
    systemNavigationBarDividerColor: Colors.white,
    systemNavigationBarIconBrightness: Brightness.dark,
  ),
);
}

有什么不明白的地方再问。 :)