flutter - 固定类型时,根据 Flutter 中选择的项目更改整个底部导航栏的背景颜色
问题描述
我正在创建这个应用程序,并添加了一个底部导航栏,除了背景颜色之外,一切都运行良好。我希望根据选择的项目来改变背景。当我使用它时它工作得很好type: BottomNavigationBarType.shifting
,但当我将它更改为type: BottomNavigationBarType.fixed
.
问题是我不喜欢“转变”的行为,我更喜欢它“固定”。
我在网上找到了这个例子,但它使用了 shift 类型:
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
backgroundColor: Colors.teal
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
backgroundColor: Colors.cyan
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
backgroundColor: Colors.lightBlue,
),
],
type: BottomNavigationBarType.shifting,
currentIndex: _selectedIndex,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.grey,
iconSize: 40,
onTap: _onItemTap,
elevation: 5
)
如何使用底部导航栏实现相同的背景颜色变化效果type: BottomNavigationBarType.fixed
?
提前致谢。
解决方案
使用BackgroundNavigationBar.backgroundColor
. 考虑文档中的这个修改示例:
class Option {
final String name;
final IconData icon;
final Color color;
const Option({
required this.name,
required this.icon,
required this.color,
});
}
class HomePageState extends State<HomePage> {
static const List<Option> options = [
Option(name: "Home", icon: Icons.home, color: Colors.red,),
Option(name: "Business", icon: Icons.business, color: Colors.green),
Option(name: "School", icon: Icons.school, color: Colors.purple),
Option(name: "Settings", icon: Icons.settings, color: Colors.pink),
];
int index = 0;
Option get option => options [index];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: Text("Index $index: ${option.name}"),
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: option.color,
type: BottomNavigationBarType.fixed,
currentIndex: index,
onTap: (value) => setState(() => index = value),
items: [
for (final option in options) BottomNavigationBarItem(
icon: Icon(option.icon),
label: option.name,
),
],
),
);
}
}
推荐阅读
- java - 无法单击按钮 org.openqa.selenium.WebDriverException:在点 (502, 85) 处不可单击。其他元素会收到点击:
- c# - Visual Studio 中的 MSBuild - 在将文件包含为内容之前移动文件 (C#)
- java - 使用外部终端窗口代替集成终端窗口
- symfony - Symfony 5 动态路由解析
- java - 如何在一个活动中处理相同布局的两个回收视图?
- laravel - 从多个关系中获取数据 laravel
- python - 使用 structlog 记录更改的对象属性
- java - apache.camel 中 Exchange 的 getIn() 与 getMessage()
- php - HTML 不解释标签
- c - 复数除法的高精度公式