How would you wait for future response for a specific amount of time?
Say, we make a http post request and await for its response before we close the http request, b
try {
var response = await Http.get("YourUrl").timeout(const Duration(seconds: 3));
if(response.statusCode == 200){
print("Success");
}else{
print("Something wrong");
}
} on TimeoutException catch (e) {
print('Timeout');
} on Error catch (e) {
print('Error: $e');
}
This example sets timeout to 3 second. If it has been 3 seconds and no response received, it will throw TimeoutException
Import this :
import 'package:http/http.dart' as Http;
import 'dart:async';
You can use Future.any
constructor to make a race condition
final result = await Future.any([
Future.value(42),
Future.delayed(const Duration(seconds: 3))
]);
You can also use Future.timout method
final result = await Future.value(42).timeout(const Duration(seconds: 3));