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(。

现在有人怎么做吗?

非常感谢!

我希望能理解你的问题。我在自己的应用程序中有以下实现,这将重建_showPage(int index(函数中的页面,其中调用不同的页面(QuestionPage、OwnQuestionPage和ProfilePage(。

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;
}
});
}
}

最新更新