如何使用HTTP请求(Flutter/Dart)检查Internet连接? [英] How do I check Internet Connectivity using HTTP requests(Flutter/Dart)?

查看:327
本文介绍了如何使用HTTP请求(Flutter/Dart)检查Internet连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个菜鸟问题,但是如果用户没有Internet连接或者获取数据的时间太长,我如何使我的响应抛出异常?

This is probably a noob question, but how do I make my response throw an exception if the user does not have an internet connection or if it takes too long to fetch the data?

Future<TransactionModel> getDetailedTransaction(String crypto) async {
//TODO Make it return an error if there is no internet or takes too long!

 http.Response response = await http.get(crypto);

  return parsedJson(response);

   }

推荐答案

您应该使用try catch块将其包围,如下所示:

You should surround it with try catch block, like so:

import 'package:http/http.dart' as http;

int timeout = 5;
try {
  http.Response response = await http.get('someUrl').
      timeout(Duration(seconds: timeout));
  if (response.statusCode == 200) {
    // do something
  } else {
    // handle it
  }
} on TimeoutException catch (e) {
  print('Timeout Error: $e');
} on SocketException catch (e) {
  print('Socket Error: $e');
} on Error catch (e) {
  print('General Error: $e');
}

如果电话知道没有连接(例如WiFi和数据连接均已关闭),则会立即引发套接字异常.

Socket exception will be raised immediately if the phone is aware that there is no connectivity (like both WiFi and Data connection are turned off).

在给定的超时时间后,将引发超时异常,例如服务器回复时间过长或用户连接非常差等.

Timeout exception will be raised after the given timeout, like if the server takes too long to reply or users connection is very poor etc.

如果响应代码不是= 200,也不要忘记处理这种情况.

Also don't forget to handle the situation if the response code isn't = 200.

这篇关于如何使用HTTP请求(Flutter/Dart)检查Internet连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆