Flutter中根据明暗主题适配SystemUI导航栏与状态栏
Flutter 明暗主题自动切换状态栏/导航栏图标颜色方案
一、全局主题配置(推荐)
直接在MaterialApp的theme和darkTheme中配置,让系统自动跟随主题切换样式,无需手动调用SystemChrome:
void main() { WidgetsFlutterBinding.ensureInitialized(); // 开启edge-to-edge模式 SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData.light().copyWith( // 浅色主题配置 appBarTheme: const AppBarTheme( systemOverlayStyle: SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarIconBrightness: Brightness.dark, // 浅色主题下状态栏图标为深色 ), ), systemNavigationBarTheme: const SystemNavigationBarThemeData( systemNavigationBarColor: Colors.transparent, systemNavigationBarIconBrightness: Brightness.dark, // 浅色主题下导航栏图标为深色 systemNavigationBarContrastEnforced: false, ), ), darkTheme: ThemeData.dark().copyWith( // 深色主题配置 appBarTheme: const AppBarTheme( systemOverlayStyle: SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarIconBrightness: Brightness.light, // 深色主题下状态栏图标为浅色 ), ), systemNavigationBarTheme: const SystemNavigationBarThemeData( systemNavigationBarColor: Colors.transparent, systemNavigationBarIconBrightness: Brightness.light, // 深色主题下导航栏图标为浅色 systemNavigationBarContrastEnforced: false, ), ), themeMode: ThemeMode.system, // 跟随系统明暗主题 home: const HomePage(), ); } }
配置完成后,无论是系统自动切换明暗,还是手动修改themeMode,状态栏和导航栏的图标颜色都会自动适配当前主题。
二、局部页面控制(AnnotatedRegion)
如果需要某个页面单独设置样式,或者更灵活地控制样式,可以用AnnotatedRegion包裹页面,结合当前主题动态生成样式:
class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { final isDarkMode = Theme.of(context).brightness == Brightness.dark; return AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle( statusBarColor: const Color.fromARGB(85, 0, 0, 0), statusBarIconBrightness: isDarkMode ? Brightness.light : Brightness.dark, systemNavigationBarColor: Colors.transparent, systemStatusBarContrastEnforced: false, systemNavigationBarContrastEnforced: false, ), child: Scaffold( body: // 你的页面内容 ), ); } }
注意事项
- 必须先调用
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge),否则透明导航栏/状态栏的设置可能不生效。 - 如果页面使用了AppBar,AppBar自带的
systemOverlayStyle会覆盖全局配置,需要在appBarTheme中统一设置样式。
内容的提问来源于stack exchange,提问作者Covex
相关产品推荐
相关产品推荐

