flutter 如何在快速浏览页面的同时处理HTTP API请求

h5qlskok  于 11个月前  发布在  Flutter
关注(0)|答案(2)|浏览(101)

对于我的场景,我已经使用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;
}
}

字符串

wwtsj6pe

wwtsj6pe1#

我找到了解决办法
要实现这一点,需要在导航时关闭http连接,因为这样做需要从http创建一个客户端,并需要在dispose方法上关闭该客户端

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

字符串
导航时关闭连接

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

vql8enpb

vql8enpb2#

如果你深入到你的代码中,并且没有任何http.Client的处理程序。你不想在UI上显示最新的响应。那么你可以遵循这种方法。
我们不能在Dart中取消Future,但我们可以停止监听流。如果你想取消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拍摄

相关问题