How do I check Internet Connectivity using HTTP requests(Flutter/Dart)?

时光怂恿深爱的人放手 提交于 2020-12-23 12:08:10

问题


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);

   }

回答1:


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');
}

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.

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




回答2:


You don't need to use http to check the connectivity yourself, simply use connectivity library




回答3:


You can use this plugin https://pub.dev/packages/data_connection_checker

So you can check prior if you have the connection, if not give a alert to the user that no internet connection. And if you have the internet connection then just proceed to your fetching part.

I will just link some resources below where it has been explained perfectly:

https://www.youtube.com/watch?v=u_Xyqo6lhFE

This is all things will be done prior to making an http call, but what if while making an http call the internet goes off then you can use the try catch block which @uros has mentioned.

Let me know if it works.



来源:https://stackoverflow.com/questions/61036643/how-do-i-check-internet-connectivity-using-http-requestsflutter-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!