关于界面切换以及底栏的实现可参考以前写的一篇文章:
Flutter实 ViewPager、bottomNavigationBar界面切换html
在pages目录下,咱们新建下面四个dart文件。java
其实这一部就是创建了底部导航栏须要的四个基本页面,有了这四个基本页面就能够制做底部tab的切换功能了。nginx
这里我只给一个页面(home_page.dart)的基础代码(后期这些代码都要更换,这里只是为了看到效果使用),而后你能够暗装一个的代码,复制到其它页面,进行修改。web
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child: Text('商城首页'),
)
);
}
}
记得其余三个页面都进行复制,并修改类名和Text文本属性。app
页面建立好之后,要使用import引入到index_page.dart中,引入后才可使用,若是不引入,VScode会很智能的报错。代码以下。less
import 'home_page.dart';
import 'category_page.dart';
import 'cart_page.dart';
import 'member_page.dart';
引入后声明一个List型变量,这个变量主要用于切换的,咱们把页面里的类,放到了这个List中。ide
List tabBarList = [
HomePage(),
CategoryPage(),
CartPage(),
MemberPage()
];
声明两个变量,并进行initState初始化:学习
int currentIndex = 0;
var currentPage;
@override
void initState() {
currentPage = tabBarList[currentIndex];
super.initState();
}
build方法咱们会返回一个Scaffold部件,在部件里咱们会添加底部导航栏,并利用onTap事件(单击事件),来改变导航栏的状态和切换页面。由于有界面变化,因此这也是要使用动态组件的缘由。ui
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
bottomNavigationBar: BottomNavigationBar(
type:BottomNavigationBarType.fixed,
currentIndex: currentIndex,
items:bottomTabs,
onTap: (index){
setState(() {
currentIndex = index;
currentPage = tabBodies[currentIndex];
});
},
),
body:currentPage
);
}
这里有句代码type:BottomNavigationBarType.fixed,这个是设置底部tab的样式,它有两种样式fixed和shifting,只有超过3个才会有区别,国人的习惯通常是使用fixed的。感兴趣的小伙伴能够自行折腾shifting模式。spa
这时候就能够启动虚拟机,进行预览了。为了更好的让小伙伴们学习,在这里给出index_page.dart文件的源码。
index_page.dart文件:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'home_page.dart';
import 'category_page.dart';
import 'cart_page.dart';
import 'member_page.dart';
class IndexPage extends StatefulWidget {
@override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage> {
// tab分组
List tabBarList = [
HomePage(),
CategoryPage(),
CartPage(),
MemberPage()
];
final List<BottomNavigationBarItem> bottomTabs = [
BottomNavigationBarItem(
icon:Icon(CupertinoIcons.home),
title:Text('首页')
),
BottomNavigationBarItem(
icon:Icon(CupertinoIcons.search),
title:Text('分类')
),
BottomNavigationBarItem(
icon:Icon(CupertinoIcons.shopping_cart),
title:Text('购物车')
),
BottomNavigationBarItem(
icon:Icon(CupertinoIcons.profile_circled),
title:Text('会员中心')
),
];
int currentIndex = 0;
var currentPage;
@override
void initState() {
currentPage = tabBarList[currentIndex];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
bottomNavigationBar: BottomNavigationBar(
type:BottomNavigationBarType.fixed,
currentIndex: currentIndex,
items:bottomTabs,
onTap: (index){
setState(() {
currentIndex = index;
currentPage = tabBarList[currentIndex];
});
},
),
body:currentPage
);
}
}
效果图:
经过这节课的学习,应该掌握以下知识点: