How to handle http GET request in an app with bottom navigation












1















I'm currently working on an app that has multiple pages and using bottom navigation bar, every page needs to send an HTTP GET request to a different API endpoint.



Right now I call the get function inside the initState() of every page. As a result, every time I tap on the navigation bar to go to the corresponding page, it will send another HTTP GET request all over again. How can I handle this? should I send the GET request from the Bottom Navigation page?



I've tried using the PageStorageKey method but I think the problem is that I called the GET method inside the initState of every page.



MyTab.dart



bottomNavigationBar: Theme(
data: Theme.of(context).copyWith(
// sets the background color of the `BottomNavigationBar`
canvasColor: Color(0xff3a3637),
// sets the active color of the `BottomNavigationBar` if `Brightness` is light
primaryColor: Color(0xffffd51e),
textTheme: Theme.of(context).textTheme.copyWith(
caption: TextStyle(color: Colors.white),
),
), // sets the inactive color of the `BottomNavigationBar`

child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: currentTab,
onTap: (int index) {
setState(() {
currentTab = index;
currentPage = pages[index];
});
},

items: <BottomNavigationBarItem>[

BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/anggota_white.png")),
title: Text(
'Anggota',
style: TextStyle(fontFamily: 'MyriadPro'),
),
),

BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/bk_white.png")),
title: Text(
"BK",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),

BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/himatif_white.png")),
title: Text(
"Himatif",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),

BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text(
"Cari",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),

BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/kkm_white.png")),
title: Text(
"KKM",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),
],
),
),


Here is one the the page,



AnggotaScreen.dart



class AnggotaScreen extends StatefulWidget {
AnggotaScreen({
Key key,
}) : super(key: key);

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

class _AnggotaScreenState extends State<AnggotaScreen> {
bool _isLoading;
var _dataAngkatan, _dataTahun;
static String _uriAngkatan;

_ambilData(String url, bool tipe) async {
final response = await http.get(url);

if (response.statusCode == 200) {
final map = json.decode(response.body);

if (tipe == true) {
setState(() {
_dataAngkatan = map;
_isLoading = false;
});
} else {
setState(() {
_dataTahun = map;
_isLoading = false;
});
}
}
}

// initState
@override
void initState() {
super.initState();
_isLoading = true;
_uriAngkatan = "2012";
_dataAngkatan = ;
_dataTahun = ;
_ambilData(Url.TAHUN_ANGGOTA, false);
_ambilData(Url.angkatan(_uriAngkatan), true);
}
..........
}


I'd like to make the page send the GET request only once on the start and hold that state until the app closed, but right now it will send the GET request every time I open that page.










share|improve this question



























    1















    I'm currently working on an app that has multiple pages and using bottom navigation bar, every page needs to send an HTTP GET request to a different API endpoint.



    Right now I call the get function inside the initState() of every page. As a result, every time I tap on the navigation bar to go to the corresponding page, it will send another HTTP GET request all over again. How can I handle this? should I send the GET request from the Bottom Navigation page?



    I've tried using the PageStorageKey method but I think the problem is that I called the GET method inside the initState of every page.



    MyTab.dart



    bottomNavigationBar: Theme(
    data: Theme.of(context).copyWith(
    // sets the background color of the `BottomNavigationBar`
    canvasColor: Color(0xff3a3637),
    // sets the active color of the `BottomNavigationBar` if `Brightness` is light
    primaryColor: Color(0xffffd51e),
    textTheme: Theme.of(context).textTheme.copyWith(
    caption: TextStyle(color: Colors.white),
    ),
    ), // sets the inactive color of the `BottomNavigationBar`

    child: BottomNavigationBar(
    type: BottomNavigationBarType.fixed,
    currentIndex: currentTab,
    onTap: (int index) {
    setState(() {
    currentTab = index;
    currentPage = pages[index];
    });
    },

    items: <BottomNavigationBarItem>[

    BottomNavigationBarItem(
    icon: ImageIcon(AssetImage("assets/icon/anggota_white.png")),
    title: Text(
    'Anggota',
    style: TextStyle(fontFamily: 'MyriadPro'),
    ),
    ),

    BottomNavigationBarItem(
    icon: ImageIcon(AssetImage("assets/icon/bk_white.png")),
    title: Text(
    "BK",
    style: TextStyle(fontFamily: 'MyriadPro'),
    ),
    ),

    BottomNavigationBarItem(
    icon: ImageIcon(AssetImage("assets/icon/himatif_white.png")),
    title: Text(
    "Himatif",
    style: TextStyle(fontFamily: 'MyriadPro'),
    ),
    ),

    BottomNavigationBarItem(
    icon: Icon(Icons.search),
    title: Text(
    "Cari",
    style: TextStyle(fontFamily: 'MyriadPro'),
    ),
    ),

    BottomNavigationBarItem(
    icon: ImageIcon(AssetImage("assets/icon/kkm_white.png")),
    title: Text(
    "KKM",
    style: TextStyle(fontFamily: 'MyriadPro'),
    ),
    ),
    ],
    ),
    ),


    Here is one the the page,



    AnggotaScreen.dart



    class AnggotaScreen extends StatefulWidget {
    AnggotaScreen({
    Key key,
    }) : super(key: key);

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

    class _AnggotaScreenState extends State<AnggotaScreen> {
    bool _isLoading;
    var _dataAngkatan, _dataTahun;
    static String _uriAngkatan;

    _ambilData(String url, bool tipe) async {
    final response = await http.get(url);

    if (response.statusCode == 200) {
    final map = json.decode(response.body);

    if (tipe == true) {
    setState(() {
    _dataAngkatan = map;
    _isLoading = false;
    });
    } else {
    setState(() {
    _dataTahun = map;
    _isLoading = false;
    });
    }
    }
    }

    // initState
    @override
    void initState() {
    super.initState();
    _isLoading = true;
    _uriAngkatan = "2012";
    _dataAngkatan = ;
    _dataTahun = ;
    _ambilData(Url.TAHUN_ANGGOTA, false);
    _ambilData(Url.angkatan(_uriAngkatan), true);
    }
    ..........
    }


    I'd like to make the page send the GET request only once on the start and hold that state until the app closed, but right now it will send the GET request every time I open that page.










    share|improve this question

























      1












      1








      1








      I'm currently working on an app that has multiple pages and using bottom navigation bar, every page needs to send an HTTP GET request to a different API endpoint.



      Right now I call the get function inside the initState() of every page. As a result, every time I tap on the navigation bar to go to the corresponding page, it will send another HTTP GET request all over again. How can I handle this? should I send the GET request from the Bottom Navigation page?



      I've tried using the PageStorageKey method but I think the problem is that I called the GET method inside the initState of every page.



      MyTab.dart



      bottomNavigationBar: Theme(
      data: Theme.of(context).copyWith(
      // sets the background color of the `BottomNavigationBar`
      canvasColor: Color(0xff3a3637),
      // sets the active color of the `BottomNavigationBar` if `Brightness` is light
      primaryColor: Color(0xffffd51e),
      textTheme: Theme.of(context).textTheme.copyWith(
      caption: TextStyle(color: Colors.white),
      ),
      ), // sets the inactive color of the `BottomNavigationBar`

      child: BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: currentTab,
      onTap: (int index) {
      setState(() {
      currentTab = index;
      currentPage = pages[index];
      });
      },

      items: <BottomNavigationBarItem>[

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/anggota_white.png")),
      title: Text(
      'Anggota',
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/bk_white.png")),
      title: Text(
      "BK",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/himatif_white.png")),
      title: Text(
      "Himatif",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: Icon(Icons.search),
      title: Text(
      "Cari",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/kkm_white.png")),
      title: Text(
      "KKM",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),
      ],
      ),
      ),


      Here is one the the page,



      AnggotaScreen.dart



      class AnggotaScreen extends StatefulWidget {
      AnggotaScreen({
      Key key,
      }) : super(key: key);

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

      class _AnggotaScreenState extends State<AnggotaScreen> {
      bool _isLoading;
      var _dataAngkatan, _dataTahun;
      static String _uriAngkatan;

      _ambilData(String url, bool tipe) async {
      final response = await http.get(url);

      if (response.statusCode == 200) {
      final map = json.decode(response.body);

      if (tipe == true) {
      setState(() {
      _dataAngkatan = map;
      _isLoading = false;
      });
      } else {
      setState(() {
      _dataTahun = map;
      _isLoading = false;
      });
      }
      }
      }

      // initState
      @override
      void initState() {
      super.initState();
      _isLoading = true;
      _uriAngkatan = "2012";
      _dataAngkatan = ;
      _dataTahun = ;
      _ambilData(Url.TAHUN_ANGGOTA, false);
      _ambilData(Url.angkatan(_uriAngkatan), true);
      }
      ..........
      }


      I'd like to make the page send the GET request only once on the start and hold that state until the app closed, but right now it will send the GET request every time I open that page.










      share|improve this question














      I'm currently working on an app that has multiple pages and using bottom navigation bar, every page needs to send an HTTP GET request to a different API endpoint.



      Right now I call the get function inside the initState() of every page. As a result, every time I tap on the navigation bar to go to the corresponding page, it will send another HTTP GET request all over again. How can I handle this? should I send the GET request from the Bottom Navigation page?



      I've tried using the PageStorageKey method but I think the problem is that I called the GET method inside the initState of every page.



      MyTab.dart



      bottomNavigationBar: Theme(
      data: Theme.of(context).copyWith(
      // sets the background color of the `BottomNavigationBar`
      canvasColor: Color(0xff3a3637),
      // sets the active color of the `BottomNavigationBar` if `Brightness` is light
      primaryColor: Color(0xffffd51e),
      textTheme: Theme.of(context).textTheme.copyWith(
      caption: TextStyle(color: Colors.white),
      ),
      ), // sets the inactive color of the `BottomNavigationBar`

      child: BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: currentTab,
      onTap: (int index) {
      setState(() {
      currentTab = index;
      currentPage = pages[index];
      });
      },

      items: <BottomNavigationBarItem>[

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/anggota_white.png")),
      title: Text(
      'Anggota',
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/bk_white.png")),
      title: Text(
      "BK",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/himatif_white.png")),
      title: Text(
      "Himatif",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: Icon(Icons.search),
      title: Text(
      "Cari",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),

      BottomNavigationBarItem(
      icon: ImageIcon(AssetImage("assets/icon/kkm_white.png")),
      title: Text(
      "KKM",
      style: TextStyle(fontFamily: 'MyriadPro'),
      ),
      ),
      ],
      ),
      ),


      Here is one the the page,



      AnggotaScreen.dart



      class AnggotaScreen extends StatefulWidget {
      AnggotaScreen({
      Key key,
      }) : super(key: key);

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

      class _AnggotaScreenState extends State<AnggotaScreen> {
      bool _isLoading;
      var _dataAngkatan, _dataTahun;
      static String _uriAngkatan;

      _ambilData(String url, bool tipe) async {
      final response = await http.get(url);

      if (response.statusCode == 200) {
      final map = json.decode(response.body);

      if (tipe == true) {
      setState(() {
      _dataAngkatan = map;
      _isLoading = false;
      });
      } else {
      setState(() {
      _dataTahun = map;
      _isLoading = false;
      });
      }
      }
      }

      // initState
      @override
      void initState() {
      super.initState();
      _isLoading = true;
      _uriAngkatan = "2012";
      _dataAngkatan = ;
      _dataTahun = ;
      _ambilData(Url.TAHUN_ANGGOTA, false);
      _ambilData(Url.angkatan(_uriAngkatan), true);
      }
      ..........
      }


      I'd like to make the page send the GET request only once on the start and hold that state until the app closed, but right now it will send the GET request every time I open that page.







      http dart flutter






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 4:56









      Muhammad Islam TaufikurahmanMuhammad Islam Taufikurahman

      164




      164
























          2 Answers
          2






          active

          oldest

          votes


















          2














          Offstage A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent.
          TickerMode which can be used to disable animations in a subtree



          https://docs.flutter.io/flutter/widgets/Offstage-class.html



          body: Stack(
          children: <Widget>[
          new Offstage(
          offstage: index != 0,
          child: new TickerMode(
          enabled: index == 0,
          child: Screen() //MainScreen(),
          ),
          ),
          new Offstage(
          offstage: index != 1,
          child: new TickerMode(
          enabled: index == 1,
          child: Screen(),
          ),
          ),
          new Offstage(
          offstage: index != 2,
          child: new TickerMode(
          enabled: index == 2,
          child: Screen(),
          ),
          ),
          new Offstage(
          offstage: index != 3,
          child: new TickerMode(
          enabled: index == 3,
          child: Screen(),
          ),
          ),
          ],
          )





          share|improve this answer































            1














            I think you are right. I have developed a similar app with similar situation, and I sent all the http request at initState of the parent page (Bottom Navigation page in your case) to avoid sending multiple http requests. Just send the request and hold the data at the parent page and pass those data down to each children pages.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54001395%2fhow-to-handle-http-get-request-in-an-app-with-bottom-navigation%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              Offstage A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent.
              TickerMode which can be used to disable animations in a subtree



              https://docs.flutter.io/flutter/widgets/Offstage-class.html



              body: Stack(
              children: <Widget>[
              new Offstage(
              offstage: index != 0,
              child: new TickerMode(
              enabled: index == 0,
              child: Screen() //MainScreen(),
              ),
              ),
              new Offstage(
              offstage: index != 1,
              child: new TickerMode(
              enabled: index == 1,
              child: Screen(),
              ),
              ),
              new Offstage(
              offstage: index != 2,
              child: new TickerMode(
              enabled: index == 2,
              child: Screen(),
              ),
              ),
              new Offstage(
              offstage: index != 3,
              child: new TickerMode(
              enabled: index == 3,
              child: Screen(),
              ),
              ),
              ],
              )





              share|improve this answer




























                2














                Offstage A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent.
                TickerMode which can be used to disable animations in a subtree



                https://docs.flutter.io/flutter/widgets/Offstage-class.html



                body: Stack(
                children: <Widget>[
                new Offstage(
                offstage: index != 0,
                child: new TickerMode(
                enabled: index == 0,
                child: Screen() //MainScreen(),
                ),
                ),
                new Offstage(
                offstage: index != 1,
                child: new TickerMode(
                enabled: index == 1,
                child: Screen(),
                ),
                ),
                new Offstage(
                offstage: index != 2,
                child: new TickerMode(
                enabled: index == 2,
                child: Screen(),
                ),
                ),
                new Offstage(
                offstage: index != 3,
                child: new TickerMode(
                enabled: index == 3,
                child: Screen(),
                ),
                ),
                ],
                )





                share|improve this answer


























                  2












                  2








                  2







                  Offstage A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent.
                  TickerMode which can be used to disable animations in a subtree



                  https://docs.flutter.io/flutter/widgets/Offstage-class.html



                  body: Stack(
                  children: <Widget>[
                  new Offstage(
                  offstage: index != 0,
                  child: new TickerMode(
                  enabled: index == 0,
                  child: Screen() //MainScreen(),
                  ),
                  ),
                  new Offstage(
                  offstage: index != 1,
                  child: new TickerMode(
                  enabled: index == 1,
                  child: Screen(),
                  ),
                  ),
                  new Offstage(
                  offstage: index != 2,
                  child: new TickerMode(
                  enabled: index == 2,
                  child: Screen(),
                  ),
                  ),
                  new Offstage(
                  offstage: index != 3,
                  child: new TickerMode(
                  enabled: index == 3,
                  child: Screen(),
                  ),
                  ),
                  ],
                  )





                  share|improve this answer













                  Offstage A widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit testing, and without taking any room in the parent.
                  TickerMode which can be used to disable animations in a subtree



                  https://docs.flutter.io/flutter/widgets/Offstage-class.html



                  body: Stack(
                  children: <Widget>[
                  new Offstage(
                  offstage: index != 0,
                  child: new TickerMode(
                  enabled: index == 0,
                  child: Screen() //MainScreen(),
                  ),
                  ),
                  new Offstage(
                  offstage: index != 1,
                  child: new TickerMode(
                  enabled: index == 1,
                  child: Screen(),
                  ),
                  ),
                  new Offstage(
                  offstage: index != 2,
                  child: new TickerMode(
                  enabled: index == 2,
                  child: Screen(),
                  ),
                  ),
                  new Offstage(
                  offstage: index != 3,
                  child: new TickerMode(
                  enabled: index == 3,
                  child: Screen(),
                  ),
                  ),
                  ],
                  )






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 2 at 5:03









                  AhmedAhmed

                  43137




                  43137

























                      1














                      I think you are right. I have developed a similar app with similar situation, and I sent all the http request at initState of the parent page (Bottom Navigation page in your case) to avoid sending multiple http requests. Just send the request and hold the data at the parent page and pass those data down to each children pages.






                      share|improve this answer




























                        1














                        I think you are right. I have developed a similar app with similar situation, and I sent all the http request at initState of the parent page (Bottom Navigation page in your case) to avoid sending multiple http requests. Just send the request and hold the data at the parent page and pass those data down to each children pages.






                        share|improve this answer


























                          1












                          1








                          1







                          I think you are right. I have developed a similar app with similar situation, and I sent all the http request at initState of the parent page (Bottom Navigation page in your case) to avoid sending multiple http requests. Just send the request and hold the data at the parent page and pass those data down to each children pages.






                          share|improve this answer













                          I think you are right. I have developed a similar app with similar situation, and I sent all the http request at initState of the parent page (Bottom Navigation page in your case) to avoid sending multiple http requests. Just send the request and hold the data at the parent page and pass those data down to each children pages.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 2 at 5:02









                          dshukertjrdshukertjr

                          1,9671930




                          1,9671930






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54001395%2fhow-to-handle-http-get-request-in-an-app-with-bottom-navigation%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              MongoDB - Not Authorized To Execute Command

                              How to fix TextFormField cause rebuild widget in Flutter

                              Npm cannot find a required file even through it is in the searched directory