Flutter中如何将appBarTheme背景色应用到BottomAppBar?
Flutter中BottomAppBar无法获取AppBar背景色的解决方法
问题原因
你没有在ThemeData里显式配置appBarTheme.backgroundColor,直接调用Theme.of(context).appBarTheme.backgroundColor会返回null。在关闭Material3的情况下,AppBar的默认背景色是继承自colorScheme.primary,而非appBarTheme中的显式配置值。
解决方案
提供两种实用的处理方式:
方式一:显式配置AppBarTheme的背景色
在ThemeData中直接指定appBarTheme的背景色,后续即可直接获取该值:
theme: ThemeData( colorSchemeSeed: Colors.blue, useMaterial3: false, appBarTheme: const AppBarTheme( backgroundColor: Colors.blue, // 显式设置AppBar背景色 ), ),
方式二:通过ColorScheme获取默认的AppBar背景色
关闭Material3时,AppBar默认使用colorScheme.primary作为背景色,直接从ColorScheme中取值即可:
bottomNavigationBar: BottomAppBar( color: Theme.of(context).colorScheme.primary, child: const Text("nav bar"), ),
兼容Material3的通用写法
如果之后可能开启Material3,推荐用这种兼容写法,适配不同主题模式下的AppBar背景色逻辑:
bottomNavigationBar: BottomAppBar( color: AppBarTheme.of(context).backgroundColor ?? Theme.of(context).colorScheme.primary, child: const Text("nav bar"), ),
内容的提问来源于stack exchange,提问作者vcs
相关产品推荐
相关产品推荐

