【发布时间】:2021-06-27 10:02:59
【问题描述】:
我正在学习 Flutter 并正在努力解决一些状态管理问题。
我有一个 HomeScreen 小部件,其中包含 Scaffold 和 BottomNavigationBar。要根据 BottomNavigationBar 中的选定选项卡切换页面,我将 PageView 与 PageController 一起使用。以下是 HomeScreen 小部件的 build 方法的外观:
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: _currentIndex == 2,
appBar: AppBar(...properties),
body: PageView(
controller: _pageController,
children: _pages,
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[...items],
currentIndex: _currentIndex,
onTap: _onItemTapped, //This changes state _currentIndex and calls the method _pageController.jumpToPage(_currentIndex);
),
);
}
-
_currentIndex最初为 0。 -
_pages是一个包含 3 个小部件的列表。 -
_pageController是简单的 PageController,initialPage 设置为 0。
如果您注意到我正在使用 extendBodyBehindAppBar: _currentIndex == 2 的属性,该属性正在使用 _currentIndex 状态,这会导致问题。
当我点击 BottomNavigationBar 上的最后一个选项卡时,_currentIndex 状态更改为 2,因此 extendBodyBehindAppBar 设置为 true,这使得整个 Scaffold 自行重建并且 PageView 的状态丢失。
如果注释掉 extendBodyBehindAppBar: _currentIndex == 2 行,那么即使 Scaffold 重建 PageView 小部件的状态也会被保留。
据我了解,即使父部件重建,Flutter 也应该保持子部件的状态,因为 WidgetTree 没有更改或重新排列。我尝试在 PageView 上使用 Key,但没有任何效果。
非常感谢任何帮助。
【问题讨论】:
标签: flutter flutter-state