Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 等待未来一段特定的时间_Asynchronous_Dart_Async Await_Flutter_Future - Fatal编程技术网

Asynchronous 等待未来一段特定的时间

Asynchronous 等待未来一段特定的时间,asynchronous,dart,async-await,flutter,future,Asynchronous,Dart,Async Await,Flutter,Future,您将如何在特定的时间内等待未来的响应 比如说,我们发出一个HTTPPOST请求,并在关闭http请求之前等待它的响应,但是,我们只等待3秒钟,否则我们关闭请求 你将如何做到这一点 差不多 Future makePostReq() async{ .... await http response for 3 secs .... if(response) { ... Do something with it } Http.close } 您可以使用Future.

您将如何在特定的时间内等待未来的响应

比如说,我们发出一个HTTPPOST请求,并在关闭http请求之前等待它的响应,但是,我们只等待3秒钟,否则我们关闭请求

你将如何做到这一点

差不多

Future makePostReq() async{
  .... 

  await http response for 3 secs

  .... 

 if(response) {
  ... Do something with it
 }

 Http.close

} 

您可以使用
Future.any
构造函数来创建竞争条件

final result = await Future.any([
  Future.value(42),
  Future.delayed(const Duration(seconds: 3))
]);
您也可以使用该方法


你可以很容易地做到

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';
Future.any([asyncfunc,…]) 下面是一个使用Remi的
未来的例子。任何首先返回未来的
解决方案都将被使用。另一个被丢弃

因此,第一个未来是您的数据收集/慢速功能,另一个是当您的通话时间过长时的回退功能

    dynamic result = await Future.any([
      getData(fakeDelay: seconds), // ← hope this returns first
      timeoutAfter(sec: timeout, onTimeout: () => 'Timed Out!', ) // ← waited too long, do this
    ]);
颤振页面中的示例 下面是颤振页面的复制/粘贴示例:

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

导入“包装:颤振/材料.省道”;
类FutureTimeoutPage扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“未来或超时页”),
),
正文:FutureAnyExample(),
);
}
}
类FutureAnyExample扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
Text('超时前完成或超时:'),
尺寸箱(高度:30,),
划船(
mainAxisAlignment:mainAxisAlignment.space,
儿童:[
提升按钮(按下时:()=>getDataOrTimeout(秒数:1,超时:3),
child:Text('In Time'),
提升按钮(按下时:()=>getDataOrTimeout(秒数:5,超时:3),
子项:文本(“太慢”)
],
)
],
);
}
未来getDataOrTimeout({int秒,int超时})异步{
///在Future.any中,根据需要放置尽可能多的异步函数。
///先完成的将被返回,其余的将被丢弃
动态结果=等待未来。任何([
getData(假延迟:秒),//← 希望这是第一次
timeoutAfter(秒:超时,onTimeout:()=>“超时!”,)//← 等得太久了,做这个吧
]);
打印(结果);
}
///模拟长时间运行的操作,如获取DB数据或API调用
未来的getData({int fakeDelay})异步{
return Future.delayed(持续时间(秒:fakeDelay),()=>“返回的数据!”);
}
///这样做以防我的长期运行操作花费太长时间
///可以运行函数或只是返回一些消息
Future timeoutAfter({int sec,Function()onTimeout})异步{
返回未来。延迟(持续时间(秒:秒),超时);
}
}

将给它一个机会。42有什么用?@RémiRousselet抱歉地回答一个老问题:这两种解决方案之间有什么区别?它们仍然可行吗?@GiacomoM第一个尝试解决2个期货,并返回第一个完成的期货。第二个函数启动一个计时器,如果future在此之前还没有完成,它将抛出,或者如果包含
onTimeout
函数,它将返回该值。我会使用第二个,因为它是专门为这个目的设计的,但它们都工作得一样好。@ThinkDigital谢谢。在此特定示例中,什么返回
const Duration
语句?只是一个
Duration
变量?我如何检查我的承诺是否得到执行?@ThinkDigital否,在这个特定的示例中,我不完全理解返回语句
const Duration(seconds:3)
I get error error:“TimeoutException”不是一种类型。在TimeoutException捕获(e){您需要添加
import'dart:async';
    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);
  }
}