unhandled socket exception with no internet connection when i set timeout duration
If you want to implement a timeout with the http package, here is how it can be done:
import 'dart:io';import 'package:http/http.dart' as http;import 'package:http/io_client.dart' as http;Future<void> login(String email, String password) async { final ioClient = HttpClient(); client.connectionTimeout = const Duration(seconds: 5); final body = { 'email': email, 'password': password }; final client = http.IOClient(ioClient); http.Response res; try { res = await client .post( '$url/login', headers: {'Content-Type': 'application/json'}, body: jsonEncode(body)); } on SocketException catch (e) { // Display an alert, no internet } catch (err) { print(err); return null; } // Do something with the response...}
You should consider using the HTTP package https://pub.dev/packages/http as it helps cleanup your code an helps with error handling.
Here's an example of a GET request using the package :
await http.get(url).then((response) async { // DO SOMETHING HERE});
response.body is your data.response.statusCode is your http status code (200, 404, 500, etc.)
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
and here's a post request with data :
var data = { "dataset1": { "key1": "value", "key2": "value", }, };await http.post(url, body: jsonEncode(data), headers: {'content-type': 'application/json'}).then((response) async { // DO SOMETHING HERE});