我目前正在构建一个 Flutter 应用程序,当使用 BottomNavigationBar 时,它会在从一个屏幕导航到另一个屏幕并再次返回时保留状态.就像它在 Spotify 移动应用程序中工作一样;如果您在其中一个主屏幕上向下导航到导航层次结构中的某个级别,则通过底部导航栏更改屏幕,然后再切换回旧屏幕,将保留用户在该层次结构中的位置,包括保留国家。
我一直在碰壁,尝试了各种不同的事情,但没有成功。
我想知道如何防止 pageChooser()
中的页面在用户点击 BottomNavigationBar 项后切换时重新构建自己,而是保留他们已经发现的状态 (这些页面都是有状态的小部件)。
import 'package:flutter/material.dart';
import './page_plan.dart';
import './page_profile.dart';
import './page_startup_namer.dart';
void main() => runApp(new Recipher());
class Recipher extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Pages();
}
}
class Pages extends StatefulWidget {
@override
createState() => new PagesState();
}
class PagesState extends State<Pages> {
int pageIndex = 0;
pageChooser() {
switch (this.pageIndex) {
case 0:
return new ProfilePage();
break;
case 1:
return new PlanPage();
break;
case 2:
return new StartUpNamerPage();
break;
default:
return new Container(
child: new Center(
child: new Text(
'No page found by page chooser.',
style: new TextStyle(fontSize: 30.0)
)
),
);
}
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: pageChooser(),
bottomNavigationBar: new BottomNavigationBar(
currentIndex: pageIndex,
onTap: (int tappedIndex) { //Toggle pageChooser and rebuild state with the index that was tapped in bottom navbar
setState(
(){ this.pageIndex = tappedIndex; }
);
},
items: <BottomNavigationBarItem>[
new BottomNavigationBarItem(
title: new Text('Profile'),
icon: new Icon(Icons.account_box)
),
new BottomNavigationBarItem(
title: new Text('Plan'),
icon: new Icon(Icons.calendar_today)
),
new BottomNavigationBarItem(
title: new Text('Startup'),
icon: new Icon(Icons.alarm_on)
)
],
)
)
);
}
}
最佳答案
为了在 BottomNavigationBar
中保持状态,您可以使用 IndexedStack
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
onTap: (index) {
setState(() {
current_tab = index;
});
},
currentIndex: current_tab,
items: [
BottomNavigationBarItem(
...
),
BottomNavigationBarItem(
...
),
],
),
body: IndexedStack(
children: <Widget>[
PageOne(),
PageTwo(),
],
index: current_tab,
),
);
}
关于dart - 使用BottomNavigationBar导航时如何在 flutter 中保留小部件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49439047/