Flutter底部导航栏BottomNavigationBar

BottomNavigationBar是底部的导航栏,一般应用在多个视图进行选择。类比于Android的底部导航栏,由Text文本和Icon图标组成。

这里创建一个List为显示内容提供容器:

static const List<Widget> _widget=<Widget>[
    Text('Index 0:首页'),Text("Index 1:通讯录"),Text("Index 2:我的")];

底部导航栏的组成部分:

bottomNavigationBar: BottomNavigationBar(items: const<BottomNavigationBarItem>[
                      BottomNavigationBarItem(icon: Icon(Icons.home),title: Text('首页')),
                      BottomNavigationBarItem(icon: Icon(Icons.contacts),title: Text('通讯录')),
                      BottomNavigationBarItem(icon: Icon(Icons.build),title: Text('我的'))
                    ]

规定底部导航栏选项卡被选中时的颜色变化:

selectedItemColor: Colors.amber

当某个选项卡被选中时调用:

onTap: _onItemTapped

通过在_onItemTapped方法中将当前选中的选项卡的下标index赋值给_selectedIndex,达到切换选项卡的效果:

void _onItemTapped(int index){
    setState(() {
      _selectedIndex=index;
    });
  }

完整代码如下:

class MyStatefulWidget extends StatefulWidget{
  MyStatefulWidget({Key key}) : super(key: key);
  //为widget创建可变状态
  _MyStatefulWidgetState createState()=>_MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget>{
  int _selectedIndex=0;//默认加载0号位
  //显示内容
  static const List<Widget> _widget=<Widget>[
    Text('Index 0:首页'),Text("Index 1:通讯录"),Text("Index 2:我的")];
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(appBar: AppBar(title: Text('底部导航栏'),),
                    //从List中根据当前选中的index取出元素显示
                    body: Center(child: _widget.elementAt(_selectedIndex),),
                    bottomNavigationBar: BottomNavigationBar(items: const<BottomNavigationBarItem>[
                      BottomNavigationBarItem(icon: Icon(Icons.home),title: Text('首页')),
                      BottomNavigationBarItem(icon: Icon(Icons.contacts),title: Text('通讯录')),
                      BottomNavigationBarItem(icon: Icon(Icons.build),title: Text('我的'))
                    ],
                    currentIndex: _selectedIndex,
                    selectedItemColor: Colors.amber,
                    //切换选项卡
                    onTap: _onItemTapped,),);
  }

  /**
   * 负责把当前点击的index赋值给_selectedIndex,实现切换
   */
  void _onItemTapped(int index){
    setState(() {
    //将当前选中的选项卡的下标赋值给_selectedIndex
      _selectedIndex=index;
    });
  }

}

发布了197 篇原创文章 · 获赞 245 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_36299025/article/details/99672185