Flutter 底部导航实现界面切换效果 BottomNavigationBar

setState()

  • state.setState()会触发该节点及以下整个子树更新
  • 动态变化的Widget的判定条件,应该显式的出现在该State的build()方法中,使得Widget树可以清晰的感知变化

BottomNavigationBar

系统自带的底部导航栏

currentIndex

标识当前选中的角标

currentIndex: 0,

items

设置底部导航的item,类型固定为BottomNavigationBarItem

items: [
         BottomNavigationBarItem(icon: Icon(Icons.home), label: "主页"),
         BottomNavigationBarItem(icon: Icon(Icons.category), label: "品类"),
         BottomNavigationBarItem(icon: Icon(Icons.settings), label: "设置"),
       ]

onTap

item的点击响应事件

onTap: (int value) {
            /**
             * 调用此方式实现界面刷新
             * */
            setState(() {
              this.currentIndex = value;
            });
          }

示例

class MyStateApp extends StatefulWidget {
  @override
  _MyStateAppState createState() => _MyStateAppState();
}

class _MyStateAppState extends State<MyStateApp> {

  //记录当前界面的角标
  int currentIndex = 0;

  //包含所有界面的数组
  List<Widget> pageList = [HomePage(), CategoryPage(), SettingPage()];

 
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MyStateApp'),
        ),
		
		//动态设置body的显示
        body: pageList[currentIndex],

        //设置底部导航栏
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: this.currentIndex,
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: "主页"),
            BottomNavigationBarItem(icon: Icon(Icons.category), label: "品类"),
            BottomNavigationBarItem(icon: Icon(Icons.settings), label: "设置"),
          ],
          //底部导航的点击事件 value: 点击的item的角标
          onTap: (int value) {
            /**
             * 调用此方式实现界面刷新
             * */
            setState(() {
              this.currentIndex = value;
            });
          },
        ),
      ),
      //定义主题样式
      theme: ThemeData(primarySwatch: Colors.blue),
    );
  }
}

/****************************下方三个代码块为独立文件,易于维护拓展*****************************/
//首页
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text("首页"),
    );
  }
}

//品类
class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text("品类"),
    );
  }
}

//设置界面
class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text("设置"),
    );
  }
}

你可能感兴趣的:(Flutter,flutter)