我已经按照以下教程在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),
);
}
}
答案 0 :(得分:0)
可以说,可以将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
}
}