How to give onPressed action to BottomNavigationBar in flutter?

Viewed 1771

I have a BottomNavigationBar in flutter,and i want to on click of the individual widgets of the BottomNavigationBar, so on press button "Add Contact" it should navigate me to the next page which is my FifthScreen.

Widget _myListView(BuildContext context) {
  return Column(children: [
    Expanded(
        child: ListView(
          padding: const EdgeInsets.only(top: 10.0),
          children: ListTile.divideTiles(
            context: context,
            tiles: [
              ListTile(
                leading: CircleAvatar(
                  backgroundImage: AssetImage('Icons.account_circle'),
                ),
                title: Text('User 1'),
                subtitle: Text('Hello'),
                onTap: () => Navigator.push(context,
                    MaterialPageRoute(builder: (context) => FourthScreen())),
              ),
            ],
          ).toList(),
        )),
    BottomNavigationBar(items: [
      BottomNavigationBarItem(icon: Icon(Icons.add), label: "Add Contact",),
      BottomNavigationBarItem(icon: Icon(Icons.group), label: "Contacts"),
      BottomNavigationBarItem(icon: Icon(Icons.settings), label: "Settings"),
    ])
  ]);
}```

3 Answers

BottomNavigationBar has an onTap method that returns an int (the current selected index of the navBar)

 BottomNavigationBar(
      onTap: (value) {
        if (value == 0) Navigator.of(context).push(...);
        if (value == 1) Navigator.of(context).push(...);
        if (value == 2) Navigator.of(context).push(...);
      },
    ),

Of course, index 0 in your case is "Add contact", index 1 is "Contacts" and so on...

Use the onTap() method of the BottomNavigationBar. More details here

The onTap: implementation is correct. But also do not forget to specify the currentIndex field of the currently selected item, so that this changes the state of the bottom navigation menu, if required of course.

Related