简体   繁体   English

如何在 flutter 中对 BottomNavigationBar 进行 onPressed 操作?

[英]How to give onPressed action to BottomNavigationBar in flutter?

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.我在 flutter 中有一个 BottomNavigationBar,我想点击 BottomNavigationBar 的各个小部件,所以按下按钮“添加联系人”它应该导航到下一页,这是我的 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"),
    ])
  ]);
}```

Use the onTap() method of the BottomNavigationBar.使用 BottomNavigationBar 的 onTap() 方法。 More details here更多细节在这里

BottomNavigationBar has an onTap method that returns an int (the current selected index of the navBar) BottomNavigationBar有一个 onTap 方法,该方法返回一个int (当前选择的 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...当然,在您的情况下,索引 0 是“添加联系人”,索引 1 是“联系人”等等......

The onTap: implementation is correct. onTap:实现是正确的。 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.但也不要忘记指定当前所选项目的currentIndex字段,这样如果需要当然会更改底部导航菜单的 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM