当我在初始化状态下运行两个函数时,如何停止冻结我的 UI?这两个函数是 API,它们从后端获取数据,我希望它显示在屏幕上。 我还想知道如何最大限度地减少获取这些数据的时间。如果我需要在多个屏幕上使用它,我如何将其保存在本地,这样每次我就不会调用浪费时间的 API。
代码:
@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!);
}
}
}
这绝对不是正常行为。我经常调用 2 个以上的 API 并且 UI 不会冻结。尝试在 --release 模式下运行您的应用程序或在真实设备上测试它,看看它是否仍然冻结。
关于本地保存响应,您可以将其缓存在后端或本地保存在 SharedPreferences 中。将响应对象保存为字符串,并在保存和读取时使用 JSON 编码/解码函数。