Arjun Mahar
Arjun Mahar

Reputation: 367

Display bottom navigation bar but none of its item is selected

This is my bottom navigation bar, Now i want to display bottomnavigationbar but initially none of its item is selected. When i set _selectedIndex to null, im getting an error. Any way to achieve this?

  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;
    });
  },
);

Upvotes: 9

Views: 1815

Answers (2)

rubStackOverflow
rubStackOverflow

Reputation: 6213

  • Define your initial or unselected as -1
  • Configure selected methods to change if state changes to -1

currentIndex: state.tabIndex == -1 ? 0 : state.tabIndex,
showSelectedLabels: state.tabIndex == -1 ? false : true,

Upvotes: 1

Siarhei Dudko
Siarhei Dudko

Reputation: 342

  // 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;
    });
  },
);

Upvotes: 1

Related Questions