ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flutter底部导航栏BottomNavigationBar

2019-08-16 10:41:11  阅读:355  来源: 互联网

标签:index title Text Icons Flutter selectedIndex 导航 BottomNavigationBar Icon


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;
    });
  }

}

标签:index,title,Text,Icons,Flutter,selectedIndex,导航,BottomNavigationBar,Icon
来源: https://blog.csdn.net/qq_36299025/article/details/99672185

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有