【问题标题】:How to handle HTTP api request while navigating pages quickly | FLUTTER | DART快速导航页面时如何处理HTTP api请求 |颤振 |镖
【发布时间】:2021-05-05 11:21:59
【问题描述】:

对于我的场景,我使用了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',
        'Content-Type': 'application/json',
      },
      body: data);
}
if (data == null) {
  response = await http.post(
    baseUrl + url,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
  );
}
Navigator.pop(Get.overlayContext);
return response;
}
}

【问题讨论】:

  • 你能提供一些代码吗?很难说如何帮助你。
  • 添加了示例基础 api 服务类
  • 您能否再具体一点您想要实现的目标?您想在使用导航器切换屏幕后终止已建立的连接?
  • 是的,如果我从主页导航而不等待http响应,仍然代码正在等待主页响应完成,然后再发送新的http响应,我认为这是因为等待功能,我需要导航时终止与 http 的连接
  • client.close() 完成了工作

标签: api flutter http dart flutter-pub


【解决方案1】:

我找到了解决办法

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

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

导航时关闭连接

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

【讨论】:

  • 这是一个很好的解决方案!不需要特殊的 API...
【解决方案2】:

如果您深入了解您的代码并且没有任何http.Client 的处理程序。而且您不希望在 UI 上显示最新的响应。那么你可以按照这个方法。

我们不能取消 Dart 中的未来,但我们肯定可以停止收听流。如果您想取消 Future,我们可以将 Future 转换为流并停止监听它。

void main() {
    // keep a reference to your stream subscription
    StreamSubscription<List> dataSub;

    // convert the Future returned by getData() into a Stream
    dataSub = getData().asStream().listen((List data) {
    updateDisplay(data);
  });

  // user navigated away!
  dataSub.cancel();
}

here拍摄

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 2022-11-03
    • 2020-12-25
    • 2021-07-05
    • 2020-09-30
    • 1970-01-01
    • 2016-02-06
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多