Flutter - Is it possible to unselect all items on bottomNavigationBar?

时间:2019-03-17 22:23:53

标签: dart flutter flutter-layout

Flutter project. I have a bottomNavigationBar, style=fixed. It has 4 items and it works fine. However, I need a way to unselect all items on this bar. It seems that it has to always have exactly 1 item selected, which generally makes sense, but for my project there are some instances where I need to have 0 items selected.

I can fake this by changing the color of the icon and text to be the same color of the inactive items, and that pretty much looks inactive, except the icon and text are slightly larger since it really is still selected.

Is there a way to actually unselect all items in a bottomNavigationBar instead of just trying to make them appear to be unselected?

2 个答案:

答案 0 :(得分:0)

不幸的是,无法将所有底部导航栏项都设置为未选中状态。一次,应将其中之一设置为选中状态。

正如您还建议的那样,唯一的解决方法是通过设置selectedItemColor的{​​{1}}等样式属性,使所有项目看起来都像“未选中”。

答案 1 :(得分:-1)

让我们使用变量 selectedIndex 来传递 BottomNavigationBar() 中的 currentIndex。

        BottomNavigationBar(
                currentIndex: selectedIndex != null ? selectedIndex : 0,
                selectedItemColor:
                    selectedIndex != null ? Colors.orange : Colors.grey,
                unselectedItemColor: Colors.grey,
                selectedLabelStyle: selectedIndex != null
                    ? TextStyle(fontSize: 16)
                    : TextStyle(fontSize: 0), // by this we can hide the label
                onTap: (index) => {
                  index == 0 && index != selectedIndex
                      ? Navigator.pushNamed(context, '/')
                      : index == 1 && index != selectedIndex
                          ? Navigator.pushNamed(context, '/page1')
                          : index == 2 && index != selectedIndex
                              ? Navigator.pushNamed(context, '/page2')
                              : index == 3 && index != selectedIndex
                                  ? Navigator.pushNamed(context, '/page3')
                                  : null
                },
                items: [
                  BottomNavigationBarItem(
                      icon: Icon(Icons.home), label: 'Home'),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.home_repair_service), label: 'Page1'),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.monetization_on), label: 'Page2'),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.text_snippet), label: 'Page3'),
                ],
              )

如果 selectedIndex 为空,我们将进行以下更改

  1. 分配 0 作为 currentIndex(我们也可以分配 1、2 或 3,具体取决于 BottomNavigationBarItems 的大小)。
  2. 将 unselectedItemColor 分配给 selectedItemColor。
  3. 在 selectedLabelStyle 中将 fontSize 指定为 0(这样标签就会消失)。