每次在Flutter中打开抽屉时,如何防止重新构建抽屉?

时间:2019-11-30 14:36:31

标签: flutter

在Flutter调试和配置文件模式下,我遇到了主要的性能问题。当我打开抽屉时,即使在配置文件模式下,我的应用程序也下降到约20 FPS。我曾经遇到过类似的问题,这些问题过去可以自己解决,因为Flutter(在启动时)喜欢使用旧版应用程序,直到我热加载或热重启为止。但是我已经尝试了一切,但我的应用程序的性能仍然无法接受。我只是想防止我的抽屉在用户每次打开时重新构造。

注意:该应用只能在发布模式下正常运行。

CustomDrawer类:

int _selectedIndex = 0;

class CustomDrawer extends StatefulWidget {
  get selectedIndex => _selectedIndex;
  set selectedIndex(int newIndex) => _selectedIndex = newIndex;
  final List<String> appRoutes = App.routes.keys.toList();

  @override
  _CustomDrawerState createState() => _CustomDrawerState();
}

class _CustomDrawerState extends State<CustomDrawer> {
  final List<DrawerItem> _drawerItems = [
    DrawerItem(
      title: "Home",
      icon: OMIcons.home,
    ),
    DrawerItem(
      title: "Assignments",
      icon: OMIcons.assignment,
    ),
    DrawerItem(
      title: "Schedule",
      icon: OMIcons.schedule,
    ),
    DrawerItem(
      title: "Subjects",
      icon: OMIcons.subject,
    ),
    DrawerItem(
      title: "Settings",
      icon: OMIcons.settings,
    ),
    DrawerItem(
      title: "Help and Feedback",
      icon: OMIcons.help,
    ),
    DrawerItem(
      title: "Upgrade",
      icon: OMIcons.star,
      color: Colors.orange,
    ),
  ];
  List<Widget> drawerOptions = [];

  @override
  void initState() {
    super.initState();
    _populateDrawerOptions();
  }

  void _populateDrawerOptions() {
    for (var d in _drawerItems) {
      var i = _drawerItems.indexOf(d);
      drawerOptions.add(CustomListTile(
        icon: d.icon,
        topContainerColor:
            _selectedIndex == i ? Color(0xffe8f0fe) : Colors.transparent,
        iconColor: _selectedIndex == i ? Color(0xff1967d2) : d.color,
        onTap: () => _onSelectItem(i),
        text: d.title,
        textColor: _selectedIndex == i ? Color(0xff1967d2) : d.color,
      ));
    }
  }

  void _onSelectItem(int index) {
    if (_selectedIndex == index) {
      Navigator.of(context).pop();
      return;
    }
    _selectedIndex = index;
    Navigator.of(context).pushReplacementNamed(
      widget.appRoutes[index],
    );
  }

  final Widget drawerHeader = SafeArea(
    top: true,
    child: Container(
      child: Text(
        "School Life",
        style: TextStyle(fontSize: 24.0, fontFamily: 'OpenSans'),
      ),
    ),
  );

  @override
  Widget build(BuildContext context) {
    final Color drawerColor = Theme.of(context).primaryColor;
    return Drawer(
      child: Container(
        color: drawerColor,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            drawerHeader,
            ListView(
              padding: const EdgeInsets.only(top: 15, right: 10),
              shrinkWrap: true,
              children: drawerOptions,
            ),
          ],
        ),
      ),
    );
  }
}

0 个答案:

没有答案