【发布时间】:2019-09-17 05:07:34
【问题描述】:
我正在制作一个包含 4 个不同页面的项目。我使用“BottomNavigationBar”小部件导航到每个页面。当按下“BottomNavigationBar”中的图标时,我会在 Scaffold 正文中显示不同的页面。我不使用任何路由,所以当用户按下 Android 时,应用程序会关闭。我不想发生的事情。
我找到的所有指南在导航时都会重新加载整个“Scaffold”,但我只想更新“Scaffold”小部件的“body”属性。当Navigation.pop() 出现时,我再次只希望“脚手架”主体发生变化。
我在同一问题上找到了a post,但答案对我不起作用。
我可以尝试的另一种解决方法是制作自定义历史列表,然后在页面更改时更新该列表。按下后退按钮时捕获 OnWillPop 事件以更新页面。我没有尝试过,因为我觉得必须有更好的方法。
显示页面的 Scaffold 小部件。
Widget createScaffold() {
return Scaffold(
backgroundColor: Colors.white,
appBar: EmptyAppBar(),
body: _displayedPage,
bottomNavigationBar: createBottomNavigationbar(),
);
}
BottomNavigationBar 小部件。
Widget createBottomNavigationbar() {
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home,
color: _selectedIndex == 0 ? selectedColor : unselectedColor),
title: new Text('Home',
style: new TextStyle(
color:
_selectedIndex == 0 ? selectedColor : unselectedColor)),
),
BottomNavigationBarItem(
icon: new Icon(Icons.show_chart,
color: _selectedIndex == 1 ? selectedColor : unselectedColor),
title: new Text('Month',
style: new TextStyle(
color:
_selectedIndex == 1 ? selectedColor : unselectedColor)),
),
BottomNavigationBarItem(
icon: Icon(Icons.history,
color: _selectedIndex == 2 ? selectedColor : unselectedColor),
title: Text('History',
style: new TextStyle(
color: _selectedIndex == 2
? selectedColor
: unselectedColor))),
BottomNavigationBarItem(
icon: Icon(Icons.settings,
color: _selectedIndex == 3 ? selectedColor : unselectedColor),
title: Text('Settings',
style: new TextStyle(
color: _selectedIndex == 3
? selectedColor
: unselectedColor)))
],
);
}
更新显示页面状态的方法。
void _onItemTapped(int index) {
_changeDisplayedScreen(index);
setState(() {
_selectedIndex = index;
});
}
void _changeDisplayedScreen(int index) {
switch (index) {
case 0:
setState(() {
_displayedPage = new LatestReadingPage();
});
break;
case 1:
setState(() {
_displayedPage = new HomeScreen();
//Placeholder
});
break;
case 2:
setState(() {
_displayedPage = new HomeScreen();
//Placeholder
});
break;
case 3:
setState(() {
_displayedPage = new HomeScreen();
//Placeholder
});
break;
default:
setState(() {
_displayedPage = new LatestReadingPage();
});
break;
}
}
}
我想要的是能够使用 Flutter Navigation 基础设施,但只在更改页面时更新 Scaffold 小部件的 body 属性。而不是整个屏幕。
很像 Youtube 应用或 Google 新闻应用。
【问题讨论】:
-
你想出解决办法了吗?
-
不是,我实现了一个解决方法。我抓住了“返回”事件,并维护了一个自定义历史列表。然后我会在页面更改时更新。
标签: dart flutter navigation