Await future for a specific time

后端 未结 2 1431
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 03:20

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

相关标签:
2条回答
  • 2020-12-10 03:42

    You can do it very easily

    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';
    
    0 讨论(0)
  • 2020-12-10 04:02

    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));
    
    0 讨论(0)
提交回复
热议问题