显示底部导航栏但未选择任何项目

A k*_*har 7 dart flutter flutter-layout

这是我的底部导航栏,现在我想显示底部导航栏,但最初没有选择它的任何项目。当我将 _selectedIndex 设置为 null 时,我收到错误。有什么办法可以实现这个目标吗?

  int _selectedIndex = 0;

  BottomNavigationBar(
  backgroundColor: Colors.blueAccent,
  unselectedItemColor: Colors.white,

  items: [
    BottomNavigationBarItem(
      icon: Icon(Icons.add),
      title: Text(''),
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.camera_alt),
      title: Text(''),
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.person),
      title: Text(''),
    ),
  ],
  currentIndex: _selectedIndex,
  onTap: (index) {
    setState(() {
      _selectedIndex = index;
    });
  },
);
Run Code Online (Sandbox Code Playgroud)

小智 1

  // set default unselected
  int _selectedIndex = -1;

  BottomNavigationBar(
  backgroundColor: Colors.blueAccent,
  unselectedItemColor: Colors.white,
  // if unselected change color to unselectedItemColor
  selectedItemColor: (_selectedIndex != -1) ? Colors.grey : Colors.white,

  items: [
    BottomNavigationBarItem(
      icon: Icon(Icons.add),
      title: Text(''),
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.camera_alt),
      title: Text(''),
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.person),
      title: Text(''),
    ),
  ],
  // if unselected change select index to 0, else you will get error
  currentIndex: (_selectedIndex != -1) ? _selectedIndex : 0,
  onTap: (index) {
    setState(() {
      _selectedIndex = index;
    });
  },
);
Run Code Online (Sandbox Code Playgroud)