如何在快速浏览页面的同时处理 HTTP api 请求 |颤振|镖

问题描述

对于我的场景,我使用 Flutter http 包来发出 http 请求......在主屏幕我必须发送大约 3 个 http 请求,因为我不得不使用 await 请求一个一个发送。

我已经使用了 BaseAPiService 类,所以所有的 api 调用都会通过,

如果我在上面的请求发生时导航到另一个地方,如何破坏该连接??否则,如果导航后应用程序也在等待之前的 Api 请求完成..

使用的示例基本 api 服务类

class ApiService {
  apiGet(url,data) async {
  Get.dialog(LoadingDialog());
  var response;
  if (data == null) {
    response = await http.get(
    baseUrl + url,headers: {
      'Accept': 'application/json','Content-Type': 'application/json',},);
}
Navigator.pop(Get.overlayContext);
return response;
}

apiPost(url,data) async {
  FocusScopeNode currentFocus = FocusScope.of(Get.context);
  if (!currentFocus.hasPrimaryFocus) {
  currentFocus.unfocus();
  }
  Get.dialog(LoadingDialog());
  var response;
  if (data != null) {
   response = await http.post(baseUrl + url,headers: {
        'Accept': 'application/json',body: data);
}
if (data == null) {
  response = await http.post(
    baseUrl + url,);
}
Navigator.pop(Get.overlayContext);
return response;
}
}

解决方法

我找到了解决方案

为了实现这个需要在导航时关闭http连接,为此需要从http创建一个客户端并且不需要在dispose方法上关闭该客户端

var client = http.Client()
var response = await client.get(url)

导航时关闭连接

void dispose(){
  super.dispose();
  client.close()
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...