【问题标题】:Flutter: How to try catch process after few secondsFlutter:几秒钟后如何尝试捕获过程
【发布时间】:2020-12-26 06:17:09
【问题描述】:

我有如下功能:

  Future getArticles() async {
    try {
      _loadingArticleController.sink.add(true);
      Response response;
      var dio = ApiProvider.dio();

      response = await dio.get("/article/get-random-lang?category=1&lang=${translations.currentLanguage}");
      var data = response.data['data'];
      print(data);
      articleList.clear();
      if (response.statusCode == 200) {

        for (int i = 0; i < data.length; i++) {
          model = articleFromJson(json.encode(data[i]));
          articleList.add(model);
        }

        // sink to the stream
        _articlesController.sink.add(articleList);
        _loadingArticleController.sink.add(false);
        await Storage.storeArticles(data);
      }
      else
      {
        throw new DioError(
          response: Response(
            statusCode: response.data['status'], 
            data: {
              'message': response.data['message']
            }
          )
        );
      }
    }
    on DioError catch (e) {
      var articles = await Storage.getArticles();
      if (articles.length > 0) {
        articleList.clear();
        for (int i = 0; i < articles.length; i++) {
          Article model = await compute(articleFromJson, json.encode(articles[i]));
          articleList.add(model);
        }
        _articlesController.sink.add(articleList);
      } else {
        _articlesController.sink.add([]);
      }
      _loadingArticleController.sink.add(false);

      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx and is also not 304.
      if (e.response != null) {
        print(e.response);
        print(e.response.headers);
        print(e.response.request);
        
      } else {
        // Something happen
        print(e);
      }
    } 
  }

在上述函数中,我有一个预期,如果函数出错,则从存储中获取数据。但是,我不知道如何使用 try catch 如果发生超时,让我们说 10 秒。

有什么想法吗?

提前致谢

【问题讨论】:

  • 解释一下你在做什么?
  • @Harsh0021 我的意思是,作为我的函数的默认值,我想从 API/web 获取数据,但如果花费的时间太长,我想从本地/文件获取数据

标签: android flutter asynchronous dart


【解决方案1】:

我有一个想法,你可以创建一个 10 秒的计时器,并将函数放在你的 try 块中。现在,如果 10 秒结束并且您希望您的函数被中断,您可以通过在函数中返回注释并调用 cancelTimer 来中断它来取消它。

Timer _timer;
  _startTimer() {
    _cancelTimer();
    _timer = Timer.periodic(Duration(seconds: 10), (timer) {
      _cancelTimer();
    });
  }

  _cancelTimer() {
    _timer?.cancel();
  }

【讨论】:

  • 嗨@Marcel,谢谢,但是可以将此逻辑放在小部件/ UI 中吗?
  • 您好,您可以创建一个 MaterialButton 来取消,并在 onpressed 函数中放置 _canceltimer()。然后在 _startTimer() 中添加获取文章代码。然后你可以用按钮或 10 秒后打断它
猜你喜欢
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
相关资源
最近更新 更多