【问题标题】:How to cancel API request when user presses back button in Flutter当用户在 Flutter 中按下返回按钮时如何取消 API 请求
【发布时间】:2022-01-16 06:32:43
【问题描述】:

我只想在用户点击返回按钮或滑回原始页面时取消某些页面加载(对 API 的请求)。

例如,当用户在“主页”选项卡中点击“文章”选项卡时,应用程序将请求 API 获取文章列表或错误消息(显示弹出窗口),但无法获取这些内容。

但目前,即使用户在请求时返回主页选项卡也不会取消请求,因此在主页选项卡上会弹出错误消息。

有什么方法可以安全地取消初始化功能如下?

Article tab

  Future<void> initialize() async {
    WidgetsBinding.instance!.addObserver(this);

    Future.delayed(const Duration(milliseconds: 250), () {
      _loadArticleContents();
    });
  }

  Future<void> _loadArticleContents() async {

    try {
      final result = await _apiClient.sendRequest(
        MatomeArticleRequest(id: _identity.id),
      );

      if (result.item2 != null) {
// I want to cancel this to be shown when user go back to some other tabs
        LoadErrorDialog.show(
          onTap: () => _navigator.pop(),
        );
        return;
      }
    } catch (e) {
      Log.debug(e);
      LoadErrorDialog.show(
        onTap: () => _navigator.pop(),
      );
    }
  }

【问题讨论】:

    标签: flutter api dart


    【解决方案1】:

    在官方页面查看这个插件 https://pub.dev/packages/http_client_helper

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多