首页 > 解决方案 > 在 Flutter 中单击具有多个片段的 Navigation Drawer 中的每个项目会重新加载屏幕

问题描述

我已经在 Flutter 中实现了一个具有多个片段的导航抽屉,如下面的教程,但是当我单击每个导航抽屉项目时,它会再次重建每个屏幕。我怎样才能让它活着?我不希望每个屏幕都重建。在此先感谢您的帮助 :)

https://medium.com/@kashifmin/flutter-setting-up-a-navigation-drawer-with-multiple-fragments-widgets-1914fda3c8a8?fbclid=IwAR2uur5NsehbJkh9FK8O6ZigmbQBx0V50i-DzyGlaJSpN7IkvijqhWL9GGw

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),
    );
  }
} 

标签: flutternavigation-drawer

解决方案


可以说,您可以将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
  }

}

推荐阅读