Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter, how to call async function (api request) under setState

I want to call an async api request inside setState but when I make setState async, It does not work properly. Otherwise, I can not await for the response. My request in controller:

 void fetchList() async {
    isLoading(true);
    try {
      var _list = await Requests.getYesillemeList();
      if (_list != null) {
        yList.value = _list;
      }
    } finally {
      reOrderList();
      isLoading(false);
    }
  }

If I call controller.fetchList() inside setState, I can not get response even it is awaiting for the response inside fetchList function. I am getting response when I make setState async, make fetchList Future of void and await for controller.fetchList inside setState but then rest of the code is not working properly. So, how can I call my api request inside setState and wait for a response.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you are using Getx, You can use GetX reactive widgets/methods

Example:

Controller

class MyClass extends GetxController{

    Rx<MyModel> yList = <MyModel>[].obs;
    RxBool isLoading = false;

      void fetchList() async {
        isLoading(true);
        try {
          var _list = await Requests.getYesillemeList();
          if (_list != null) {
            yList.value = _list;
          }
        } finally {
          reOrderList();
          isLoading(false);
        }
      }

}

Widget/Page

class DashboardPage extends GetView<MyClass>{
    @override
    Widget build(BuildContext context) {
        controller.fetchList();
        return Obx(() => Text("${controller.yList.length}"));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading