Flutter底部導航欄BottomNavigationBar頁面狀態保持解決方案

在實際應用開發中,一般應用的首頁面會有這種結構,在Flutter應用開發中,有多種方式來實現這種結構佈局,在《flutter底部導航欄》一文中有描述。

在這裡是通過 BottomNavigationBar + BottomNavigationBarItem,然後頁面主體結是通過Scaffold的body配置的動態從頁面List中取Widget,也就是說先把三個tab頁面存放在了List中,然後根據不同的選擇標籤來加載不同的頁面顯示

上述這種寫法造成的結果就是每當切換一次頁面時,對應的tab頁面就會重新初始化加載一次,這樣的效果,在實際應用中是體驗非常不好的,同時在應用程序中也會造成資源浪費、流量浪費等種種問題。

Flutter底部導航欄BottomNavigationBar頁面狀態保持解決方案

直接上代碼

<code>///應用入口

main() =>
runApp(MaterialApp(
home: FirstPage(),),);

class FirstPage extends StatefulWidget {
@override
State<statefulwidget> createState() {
return FirstThemState();
}
}
class FirstThemState extends State<firstpage> {

///選中的標籤
int _tabIndex =0;
///圖標區
List<icon> normalIcon = [
Icon(Icons.home),
Icon(Icons.message),
Icon(Icons.people)
];

List<string> normalTitle =[
"首頁",
"消息",
"我的"
];

List<widget> bodyWidgetList=[
ScffoldHomeItemPage(0),
ScffoldHomeItemPage1(1),
ScffoldHomeItemPage2(2),
];

@override
Widget build(BuildContext context) {
///Scaffold 用來搭建頁面的主體結構
return Scaffold(
///頁面的頭部
appBar: AppBar(title: Text("標題"),),
///頁面的主內容區

///可以是單獨的StatefulWidget 也可以是當前頁面構建的如Text文本組件
body:bodyWidgetList[_tabIndex],
///底部導航欄
bottomNavigationBar: buildBottomNavigation(),
);
}


///構建底部導航欄
BottomNavigationBar buildBottomNavigation(){

return new BottomNavigationBar(
items: <bottomnavigationbaritem>[
new BottomNavigationBarItem(
icon: normalIcon[0], title: Text(normalTitle[0])),
new BottomNavigationBarItem(
icon: normalIcon[1], title: Text(normalTitle[1])),
new BottomNavigationBarItem(
icon: normalIcon[2], title: Text(normalTitle[2])),
],
///顯示效果
type: BottomNavigationBarType.fixed,
///當前選中的頁面
currentIndex: _tabIndex,
///導航欄的背景顏色
backgroundColor: Colors.white,
///選中時圖標與文字的顏色
// fixedColor: Colors.deepPurple,
///選中時圖標與文字的顏色
selectedItemColor: Colors.blue,
///未選中時圖標與文字的顏色
unselectedItemColor: Colors.grey,
///圖標的大小
iconSize: 24.0,
///點擊事件
onTap: (index) {
setState(() {
_tabIndex = index;
});
},
);

}
}/<bottomnavigationbaritem>/<widget>/<string>/<icon>/<firstpage>/<statefulwidget>/<code>

解決方案如下

<code>class FirstThemState extends State<firstpage> {
.... ....
@override
Widget build(BuildContext context) {
///Scaffold 用來搭建頁面的主體結構
return Scaffold(
///頁面的頭部
appBar: AppBar(title: Text("標題"),),
///頁面的主內容區
body:buildBodyFunction(),
///底部導航欄
bottomNavigationBar: buildBottomNavigation(),
);
}

Widget buildBodyFunction(){
///幀佈局結合透明佈局
return Stack(children: <widget>[
Opacity(opacity: _tabIndex==0?1:0,child: ScffoldHomeItemPage(0),),
Opacity(opacity: _tabIndex==1?1:0,child: ScffoldHomeItemPage(1),),
Opacity(opacity: _tabIndex==2?1:0,child: ScffoldHomeItemPage(2),),
],);
}

}/<widget>/<firstpage>/<code>

完畢


分享到:


相關文章: