Flutter: Do I need to cache widget in onGenerateRoute

两盒软妹~` 提交于 2019-12-11 05:14:20

问题


In onGenerateRoute method in MaterialApp, it looks wasteful to create Widgets every time, route is changed and Widget will also lose context. Should these widgets new Desktop(sugar) be cached and reuse?

class AppComponentState extends State<AppComponent> implements SugarBuilder {
  Sugar sugar;

  _getRoute(RouteSettings settings) {
    final List<String> path = settings.name.split('/');
    if (path[0] != '') return null;
    if (path[1] == 'sugar') {
      if (sugar == null) {
        return Navigator.pushNamed(context, '/login');
      } else {
        if (path[2] == 'module') {
          return new ModulePage(sugar); // need to cache?
        } else {
          return new Desktop(sugar); // need to cache?
        }
      }
    }
    return null;
  }

  Widget build(BuildContext context) {
    return new MaterialApp(
       ...
       onGenerateRoute: _getRoute,
    );
  }
}

回答1:


Creating new Widget objects should generally be cheap. Flutter's widget framework will take care of updating the render tree when your widgets produce a different render objects. If you have a lot of global state for your app, you can store it in model objects and then pass them to the widgets as needed.



来源:https://stackoverflow.com/questions/45728153/flutter-do-i-need-to-cache-widget-in-ongenerateroute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!