How can I stop freezing my UI when I run two functions in the init state? Those two functions are the APIs which are getting me data from backend and I want it to display on screen. Also I want to know how can I minimize the time of getting those data. and If I need that that on multiple screen how can I save it locally so that every time I am not calling the API which wastes my time.
Code:
@override
void onInit() {
getCustomerList();
getProductList();
super.onInit();
}
Future<void> getCustomerList() async {
List<CustomerModel> newItems = (await BaseClient.safeApiCall(
ApiConstants.GET_CUSTOMER_LIST,
RequestType.get,
headers: await BaseClient.generateHeaders(),
queryParameters: {
'\$count': true,
},
onSuccess: (json) {
List<CustomerModel>? customers;
if (json.data['value'] != null) {
customers = [];
json.data['value'].forEach((v) {
customers?.add(CustomerModel.fromJson(v));
});
}
return customers;
},
onError: (e) {},
));
for (CustomerModel customer in newItems) {
if (customer.companyName != null) {
customerFilters.add(customer.customerName!);
}
}
}
Future<void> getProductList() async {
List<ProductModel> newItems = (await BaseClient.safeApiCall(
ApiConstants.GET_PRODUCT_LIST,
RequestType.get,
headers: await BaseClient.generateHeaders(),
queryParameters: {
'\$count': true,
},
onSuccess: (json) {
List<ProductModel>? products;
if (json.data['value'] != null) {
products = [];
json.data['value'].forEach((v) {
products?.add(ProductModel.fromJson(v));
});
}
return products;
},
onError: (e) {},
));
for (ProductModel products in newItems) {
if (products.productName != null) {
productFilters.add(products.productName!);
}
}
}
This is definitely not normal behavior. I often call more than 2 APIs and UI doesn't freeze. Try running your app in --release mode or test it on a real device and see if it still freezes.
Regarding saving the response locally, you either cache it in the backend or save it locally in SharedPreferences. Save the response object as a String and use JSON Encode/Decode functions when saving and reading it.