代码之家  ›  专栏  ›  技术社区  ›  Rami Dhouib

Flutter:如果等待时间超过2秒,则执行操作

  •  0
  • Rami Dhouib  · 技术社区  · 9 月前
    final response = await _errorReportRepository.sendErrorReport(event.errorReport);
    

    嗨,如果等待时间超过2秒,我想做一个操作,但不停止进程。

    举个例子。如果需要2秒以上,请在2秒后直接将变量更改为true。

    1 回复  |  直到 9 月前
        1
  •  1
  •   Melvin Kosisochukwu    9 月前
    Future<void> handleErrorReport() async {
      bool isTimeout = false;
      Timer? timeoutTimer;
    
      // Start a timer to change the variable after 2 seconds
      timeoutTimer = Timer(Duration(seconds: 2), () {
        isTimeout = true;
        print('Timeout reached, isTimeout set to true');
      });
    
      try {
        await _errorReportRepository.sendErrorReport(event.errorReport);
        
        // If sendErrorReport completes first, cancel the timer
        timeoutTimer.cancel();
        print('Error report sent successfully.');
      } catch (e) {
        print('Error occurred: $e');
      }
    }
    

    如果错误报告future超过2秒,则将变量timeout设置为true,但如果错误future在2秒前解决,则将取消超时。

    另一种选择是使用Future.any,这将竞争两个期货,如果错误报告在2秒前解决,则将忽略超时,否则超时期货将解决。