代码之家  ›  专栏  ›  技术社区  ›  Pushan Gupta

等待未来一段特定的时间

  •  5
  • Pushan Gupta  · 技术社区  · 6 年前

    你将如何等待未来的回应一个特定的时间量?

    比方说,我们发出一个httppost请求并等待它的响应,然后关闭http请求,但是,我们只等待3秒,否则就关闭请求。

    你怎么做到的?

    像这样的

    Future makePostReq() async{
      .... 
    
      await http response for 3 secs
    
      .... 
    
     if(response) {
      ... Do something with it
     }
    
     Http.close
    
    } 
    
    1 回复  |  直到 6 年前
        1
  •  26
  •   Nate Bosch    6 年前

    你可以用 Future.any 构造一个竞赛条件

    final result = await Future.any([
      Future.value(42),
      Future.delayed(const Duration(seconds: 3))
    ]);
    

    Future.timout 方法

    final result = await Future.value(42).timeout(const Duration(seconds: 3));
    
        2
  •  9
  •   Sanjayrajsinh    5 年前

    你做起来很容易

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

    本例将超时设置为3秒。如果已经3秒没有收到响应,它将抛出 TimeoutException

    导入此项:

    import 'package:http/http.dart' as Http;
    import 'dart:async';
    
        3
  •  2
  •   Baker    4 年前

    未来。有吗([ 异步函数

    下面是一个使用Remi Future.any 首先返回的未来将被使用的解决方案。另一个被丢弃。

    因此,第一个未来是您的数据收集/慢功能,另一个是当您的调用花费太长时间时的回退功能。

        dynamic result = await Future.any([
          getData(fakeDelay: seconds), // ← hope this returns first
          timeoutAfter(sec: timeout, onTimeout: () => 'Timed Out!', ) // ← waited too long, do this
        ]);
    

    颤振页面中的示例

    下面是颤振页面的复制/粘贴示例:

    (查看调试/运行输出窗口中的消息)

    import 'package:flutter/material.dart';
    
    class FutureTimeoutPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Future or Timeout Page'),
          ),
          body: FutureAnyExample(),
        );
      }
    }
    
    class FutureAnyExample extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Complete before timeout or timeout:'),
            SizedBox(height: 30,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(onPressed: () => getDataOrTimeout(seconds: 1, timeout: 3),
                    child: Text('In Time')),
                ElevatedButton(onPressed: () => getDataOrTimeout(seconds: 5, timeout: 3),
                    child: Text('Too Slow'))
              ],
            )
          ],
        );
      }
    
      Future<void> getDataOrTimeout({int seconds, int timeout}) async {
        /// In Future.any, put as many async functions as you need.
        /// Whichever completes first, will be returned. All others are discarded
        dynamic result = await Future.any([
          getData(fakeDelay: seconds), // ← hope this returns first
          timeoutAfter(sec: timeout, onTimeout: () => 'Timed Out!', ) // ← waited too long, do this
        ]);
    
        print(result);
      }
    
      /// Mock of a long-running operation like getting DB data, or API call
      Future<String> getData({int fakeDelay}) async {
        return Future.delayed(Duration(seconds: fakeDelay), () => 'Data returned!');
      }
    
      /// Do this in case my long-running op takes too long
      /// Can run a function or just return some message
      Future<dynamic> timeoutAfter({int sec, Function() onTimeout}) async {
        return Future.delayed(Duration(seconds: sec), onTimeout);
      }
    }