我在写首页框架时,用的是BottomNavigationBar和PageView。
关键点在于:让只想被初始化一次的widget with AutomaticKeepAliveClientMixin,然后覆盖方法
@override
bool get wantKeepAlive => true;
主页框架:
import 'package:flutter/material.dart';
import 'MainPageModelView.dart';
import 'MainPageDrawView.dart';
import 'MainPageDocView.dart';
import 'MainPageTaskView.dart';
import 'MainPageBoardView.dart';
class MainPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Main',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Main'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentIndex = 0;
List<Widget> tabList= [];
PageController pageController;
@override
void initState() {
super.initState();
pageController = PageController(initialPage: currentIndex);
tabList.add(MainPageModelView());
tabList.add(MainPageDrawView());
tabList.add(MainPageDocView());
tabList.add(MainPageTaskView());
tabList.add(MainPageBoardView());
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: PageView(
controller: pageController,
scrollDirection: Axis.horizontal,
children: tabList,
onPageChanged: (int index){
setState(() {
currentIndex = index;
});
},
),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: currentIndex,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.airplanemode_active), title: Text("模型")),
BottomNavigationBarItem(
icon: Icon(Icons.show_chart), title: Text("图纸")),
BottomNavigationBarItem(
icon: Icon(Icons.data_usage), title: Text("文档")),
BottomNavigationBarItem(
icon: Icon(Icons.transfer_within_a_station), title: Text("任务")),
BottomNavigationBarItem(
icon: Icon(Icons.dashboard), title: Text("看版")),
],
onTap: (int index) {
setState(() {
currentIndex = index;
// pageController.animateToPage(currentIndex, duration: Duration(milliseconds: 200), curve: Curves.easeIn);
pageController.jumpToPage(index);
});
},
),
// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
tab页面
import 'package:flutter/material.dart';
class MainPageModelView extends StatefulWidget {
MainPageModelView({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
// 这里是关键
class _MyHomePageState extends State<MainPageModelView> with AutomaticKeepAliveClientMixin{
@override
void initState() {
super.initState();
print('model');
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
);
}
// 这里。。。。。。。。。。
@override
bool get wantKeepAlive => true;
}
如此设置,_MyHomePageState的initState方法便只会初始化一次,再切换底部tab时,展示的是保存了状态数据的原页面。
欢迎关注我的公众号:Flutter和Dart开发实践
让我们共同学习进步,It is never too late to learn!

网友评论