Display bottom navigation bar but none of its item is selected

Viewed 816

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