Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

   }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...