此blog显示了如何使用PageStorage
保留页面状态
此blog在每个屏幕上显示多个导航。底部导航栏在所有屏幕上均保持不变
但是如何使BottomNavigationBar
在某些屏幕上显示/隐藏?说,登录/注册/成功的屏幕?试图为BottomNavigationBar
创建一个有状态的窗口小部件,但是每次使用导航栏时,都会重置导航栏的selectedIndex。我似乎无法使其正常工作。
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Text('app_screen'),
bottomNavigationBar: AppBottomNavigationController(),
);
}
}
app_bottom_navigation_controller.dart
class AppBottomNavigationController extends StatefulWidget {
@override
_AppBottomNavigationControllerState createState() =>
_AppBottomNavigationControllerState();
}
class _AppBottomNavigationControllerState
extends State<AppBottomNavigationController> {
int currentIndex = 0;
final List<Widget> pages = [];
final PageStorageBucket bucket = PageStorageBucket();
@override
void initState() {
pages.addAll([
HomeScreen(
key: PageStorageKey('home_screen'),
),
SearchScreen(
key: PageStorageKey('search_screen'),
),
AccountScreen(
key: PageStorageKey('account_screen'),
)
]);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageStorage(
child: pages[currentIndex],
bucket: bucket,
),
bottomNavigationBar: _bottomNavigationBar(currentIndex),
);
}
Widget _bottomNavigationBar(int selectedIndex) {
return BottomNavigationBar(
currentIndex: selectedIndex,
onTap: (index) => setState(() => currentIndex = index),
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text('Search'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Account'),
),
],
);
}
}
然后在account.dart
屏幕下,我有account_bag.dart
和account_successful.dart
屏幕。我想在account_bag.dart
屏幕上显示底部导航栏,而在account_successful.dart
屏幕上显示导航栏。