1

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.

3
  • are you using Getx? Commented May 27, 2022 at 12:28
  • @suzan yes I use Getx. Commented May 27, 2022 at 12:31
  • 1
    In that case, you do not need to use setState to update the data. Just use Getx reactive methods Commented May 27, 2022 at 12:31

1 Answer 1

1

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}"));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.