Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give onPressed action to BottomNavigationBar in flutter?

Tags:

flutter

dart

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


2 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...

like image 107
Luis Utrera Avatar answered Oct 19 '25 17:10

Luis Utrera


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.

like image 42
greengo Avatar answered Oct 19 '25 15:10

greengo