BottomNavigationBar+List<Widget>无法实现,BottomNavigationBar+PageView可以。写法如下:
///BottomNavigationBar+PageView切换页面保持状态不变
class TabbarPage extends StatefulWidget {
const TabbarPage({Key? key}) : super(key: key);
@override
_TabbarPageState createState() => _TabbarPageState();
}
class _TabbarPageState extends State<TabbarPage> {
late int _currentIndex;
late List<Widget> _pages;
late PageController _controller;
List<BottomNavigationBarItem> getItems(){
return [
BottomNavigationBarItem(
icon: Image.asset(R.assetsImgXingxing, width: 20, height: 20, color: Colors.grey,),
activeIcon: Image.asset(R.assetsImgXingxing, width: 20, height: 20, color: Colors.blue,),
label: 'tabbar1',
),
BottomNavigationBarItem(
icon: Image.asset(R.assetsImgDun, width: 20, height: 20, color: Colors.grey,),
activeIcon: Image.asset(R.assetsImgDun, width: 20, height: 20, color: Colors.blue,),
label: 'tabbar2',
),
BottomNavigationBarItem(
icon: Image.asset(R.assetsImgTalk, width: 20, height: 20, color: Colors.grey,),
activeIcon: Image.asset(R.assetsImgTalk, width: 20, height: 20, color: Colors.blue,),
label: 'tabbar3',
),
];
}
@override
void initState() {
// TODO: implement initState
super.initState();
_currentIndex = 0;
_pages = [
///widget
FultterStart1(),
FultterStart2(),
FultterStart3(),
];
_controller = PageController(initialPage: 0);
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
_controller.dispose();
}
void _onTap(int index){
_controller.jumpToPage(index);
}
void _onPageChange(int index){
if (index != _currentIndex) {
setState(() {
_currentIndex = index;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView.builder(
physics: NeverScrollableScrollPhysics(),
controller: _controller,
itemCount: _pages.length,
itemBuilder: (BuildContext context, int index){
return _pages[index];
},
onPageChanged: _onPageChange,
),
bottomNavigationBar: BottomNavigationBar(
items: getItems(),
currentIndex: _currentIndex,
onTap: _onTap,
),
);
}
}
完成BottomNavigationBar+PageView后还差一步:
1、在子widget中state方法混入 with AutomaticKeepAliveClientMixin
class FultterStart1 extends State<FultterStart> with AutomaticKeepAliveClientMixin
2、在state方法中的build方法中添加super.build(context);
@override
Widget build(BuildContext context) {
super.build(context); ///
return Scaffold(
appBar: AppBar(
3、在state方法中添加
@override
bool get wantKeepAlive => true; ///保持当前页面状态