Reputation: 667
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.
Upvotes: 1
Views: 1725
Reputation: 4767
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}"));
}
}
Upvotes: 1