flutter - 在 Flutter 中单击具有多个片段的 Navigation Drawer 中的每个项目会重新加载屏幕
问题描述
我已经在 Flutter 中实现了一个具有多个片段的导航抽屉,如下面的教程,但是当我单击每个导航抽屉项目时,它会再次重建每个屏幕。我怎样才能让它活着?我不希望每个屏幕都重建。在此先感谢您的帮助 :)
class DrawerItem {
String title;
IconData icon;
DrawerItem(this.title, this.icon);
}
class HomePage extends StatefulWidget {
final drawerItems = [
new DrawerItem("Sales", Icons.shopping_basket),
new DrawerItem("Items", Icons.category),
new DrawerItem("Setting", Icons.settings)
];
@override
State<StatefulWidget> createState() {
return new _HomepageState();
}
}
class _HomepageState extends State<HomePage> with TickerProviderStateMixin {
int _selectedDrawerIndex = 0;
_getDrawerItemWidget(int pos) {
switch (pos) {
case 0:
return new SaleGrid();
case 1:
return new ItemsList();
default:
return new Text("Error");
}
}
_onSelectItem(int index) {
setState(() => _selectedDrawerIndex = index);
Navigator.of(context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
var drawerOptions = <Widget>[];
for (var i = 0; i < widget.drawerItems.length; i++) {
var d = widget.drawerItems[i];
drawerOptions.add(new ListTile(
leading: new Icon(d.icon),
title: new Text(d.title),
selected: i == _selectedDrawerIndex,
onTap: () => _onSelectItem(i),
));
}
return new Scaffold(
appBar: new AppBar(
// here we display the title corresponding to the fragment
// you can instead choose to have a static title
title: new Text(widget.drawerItems[_selectedDrawerIndex].title),
),
drawer: new Drawer(
child: new Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text('Kimsung'),
accountEmail: Text('kimsung@vehha.com.kh'),
currentAccountPicture: ClipOval(
child: Image.asset(
'assets/profile.jpg',
fit: BoxFit.cover,
),
),
),
new Column(children: drawerOptions)
],
),
),
body: _getDrawerItemWidget(_selectedDrawerIndex),
);
}
}
解决方案
可以说,您可以将AutomaticKeepAliveClientMixin添加到您的Drawer
片段中,并将自动保持活动标志设置true
为以及super.build()
在构建方法中调用。
class Fragment1 extends StatelessWidget with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
// return your widget tree
}
}
推荐阅读
- mysql - 查询内连接3张表
- python - 调用带有参数的.Net函数形式python(通过引用传递)
- java - 所有后续 servlet 请求都可以立即写入 ConcurrentHashMap 吗?
- sql - 将复杂的 Pivot SQL 查询转换为 Laravel Eloquent 关系
- javascript - 我对 Firebase .setBackgroundMessageHandler 的调用有什么问题?
- python-3.x - python 3 - 为什么在寻找最大 ord() 值时 for 循环不起作用?
- python - 如何在泛型类的 __init__ 中使用默认值?
- vba - 如何在 MS Access 中比较 2 个表单的值?
- r - ggplot2 中的 ecdf 绘图错误:未知颜色名称
- eclipse - 无法从 maven 获取 datanuecleus 3.1.3