简体   繁体   English

Flutter TabBarView 不断调用构建器

[英]Flutter TabBarView keeps calling builders

I have a StatelessWidget widget for my tabBar which contains 2 statefulWidgets.我的 tabBar 有一个 StatelessWidget 小部件,其中包含 2 个 statefulWidget。 The thing is that when clicking on manager to watch all my tabs(landing on my first tab as default) the tab1 widget builder keeps being called.问题是,当单击管理器查看我的所有选项卡(默认登录我的第一个选项卡)时,会不断调用 tab1 小部件构建器。

I have already tried this 2 approaches but they did not work:我已经尝试过这两种方法,但它们不起作用:

Multi tab / page view in flutter 颤振中的多标签/页面视图

Flutter Switching to Tab Reloads Widgets and runs FutureBuilder Flutter 切换到 Tab 重新加载小部件并运行 FutureBuilder

It's really annoying because in some widgets I need to make some http requests and they also kept being called as well.这真的很烦人,因为在某些小部件中,我需要发出一些 http 请求,而且它们也一直被调用。

 body:  TabBarView(
        children: <Widget>[
          Tab1Page(),
          Tab2Page(),

here'smy tab1 page, which is a stateFulWidget这是我的 tab1 页面,这是一个 stateFulWidget

Widget build(BuildContext context) {
// TODO: implement build
print("tab1: Builder");
return ScopedModelDescendant<MainModel>(
  builder: (BuildContext context, Widget child, MainModel model) {
    List<SolicitudDto> listadoSolicitudesAprobadas =
        model.obtenerSolicitudesPendientes();

    return Scaffold(
      body: ListView(
        children: <Widget>[
          _buildCards(context, listadoSolicitudesAprobadas)
        ],
      ),
    );
  },
);

} }

This is a print capture of my debugger:这是我的调试器的打印捕获:

在此处输入图片说明

In case you want to keep the state of your screen in your TabBarView, you can use the mixin class called AutomaticKeepAliveClientMixin in your State class.如果您想在 TabBarView 中保留屏幕状态,可以在 State 类中使用名为AutomaticKeepAliveClientMixin的 mixin 类。

After that you have to override the wantKeepAlive method and return true .之后,您必须覆盖wantKeepAlive方法并返回true

I wrote a post about that here: https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc我在这里写了一篇关于这个的帖子: https : //medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

UPDATE更新

You could try this way to avoid request data every time you switch tabs.您可以尝试这种方式以避免每次切换标签时都请求数据。

  //global variable at your state class

  List<SolicitudDto> listadoSolicitudesAprobadas; 


  Widget build(BuildContext context) {
  // TODO: implement build
  print("tab1: Builder");
  return ScopedModelDescendant<MainModel>(
    builder: (BuildContext context, Widget child, MainModel model) {
         if (listadoSolicitudesAprobadas == null){
          listadoSolicitudesAprobadas =   model.obtenerSolicitudesPendientes();
        }

      return Scaffold(
        body: ListView(
          children: <Widget>[
            _buildCards(context, listadoSolicitudesAprobadas)
          ],
        ),
      );
    },
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM