【发布时间】: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