flutter - Flutter - 底部导航 - 如何重建页面?
问题描述
我有一个包含三个页面的应用程序,用户可以使用底部导航栏进行导航。尽管如此,我希望在用户返回时重建三个页面之一(因此:删除当前状态并从头开始重新渲染)。
我的导航代码如下。
三页选项:
static List<Widget> _widgetOptions = <Widget>[
PostFeed(),
Profile(),
HabitList(),
];
在页面选项之间切换(稍后在底部导航中):
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
在脚手架:
body: _widgetOptions.elementAt(_selectedIndex),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
),
BottomNavigationBarItem(
icon: Icon(Icons.list),
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
使用此代码,当我在它们之间切换时,所有页面的状态都保持不变。当用户单击特定的底部导航图标时,我现在只想动态加载一个(PostFeed)。
有谁现在如何做到这一点?
提前谢谢了!
解决方案
I hope i understand your Question. I have the following Implementation in my own app and this rebuilds the pages in the _showPage(int index) function where the different pages are called (QuestionPage, OwnQuestionPage and ProfilPage).
class OpinionPage extends StatefulWidget {
@override
_OpinionPageState createState() => _OpinionPageState();
}
class _OpinionPageState extends State<OpinionPage> {
int currentPageNumber;
final List<Widget> pages = [
QuestionPage(),
OwnQuestionPage(),
ProfilPage(),
];
Widget currentPage = QuestionPage();
final PageStorageBucket bucket = PageStorageBucket();
@override
void initState() {
currentPageNumber = 0;
SystemSettings.allowOnlyPortraitOrientation();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageStorage(bucket: bucket, child: currentPage),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.question_answer, color: currentPageNumber == 0 ? primaryBlue : Colors.grey),
title: Text(
'Fragen',
style: TextStyle(color: currentPageNumber == 0 ? primaryBlue : Colors.grey),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.add_circle, color: currentPageNumber == 1 ? primaryBlue : Colors.grey),
title: Text(
'Meine Fragen',
style: TextStyle(color: currentPageNumber == 1 ? primaryBlue : Colors.grey),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.person, color: currentPageNumber == 2 ? primaryBlue : Colors.grey),
title: Text(
'Profil',
style: TextStyle(color: currentPageNumber == 2 ? primaryBlue : Colors.grey),
),
),
],
onTap: (int index) => _showPage(index),
),
);
}
void _showPage(int index) {
setState(() {
switch (index) {
case 0:
currentPage = QuestionPage();
currentPageNumber = 0;
break;
case 1:
currentPage = OwnQuestionPage();
currentPageNumber = 1;
break;
case 2:
currentPage = ProfilPage();
currentPageNumber = 2;
break;
}
});
}
}
推荐阅读
- react-native - Android 存储 api 响应控制的缓存 http->cache (React-Native)
- dependency-injection - 有没有办法通过 .NET 依赖注入有条件地将类型注册为后备?
- c# - 正则表达式 - 空白无法获取整数值
- json - Vue - 无法将值从方法属性传递给数据对象
- c++ - 如何通过模块化解决这个问题?
- azure - 用于编辑/添加规则的 Azure 存储 Blob 生命周期管理角色
- scala - 将数据插入到具有更改架构的增量表中
- node.js - rxjs firstValueFrom 从不解析
- android - 将数据动态添加到更多 TextView
- momentjs - moment.js 和 2021 年 10 月奇怪的结果