如何在等待功能中添加超时

问题描述

我有这样的功能

aa() async {
    try{
      tz.initializeTimeZones();
      var detroit = tz.getLocation('xxx');
      tz.setLocalLocation(detroit);
      DateTime v = await NTP.Now();
      DateTime today = tz.TZDateTime.from(v,detroit);
      if(today==...){
        // do something
      }else{
        // do something
      }
    }catch(err){
      throw("err");
    }
  }

我想在await NTP.Now();中设置超时,所以在等待5秒钟以上之后,我想抛出错误超时...有没有办法做到这一点? 我一直在关注此Dart timeout on await Future,但在将其实现到我的代码中时遇到了麻烦

解决方法

我认为这可能对您有帮助。

Future.delayed(Duration(seconds: 5),() { 
    //do something
   });