简体   繁体   中英

Flutter TabBarView keeps calling builders

I have a StatelessWidget widget for my tabBar which contains 2 statefulWidgets. 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.

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

It's really annoying because in some widgets I need to make some http requests and they also kept being called as well.

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

here'smy tab1 page, which is a 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.

After that you have to override the wantKeepAlive method and return true .

I wrote a post about that here: 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)
          ],
        ),
      );
    },
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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