flutterdartasynchronousasync-await

Flutter:Do an operation if await takes more then 2 seconds


final response = await _errorReportRepository.sendErrorReport(event.errorReport);

Hi,I want to do an operation if this await takes more than 2 seconds and not stop the process.

Like an example. If it takes more than 2 seconds, change a variable to true directly after 2 seconds.


Solution

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

    This will set the variable timeout to true if the error report fututre takes more than 2 seconds but will cancel the timeout if the error future resolves before 2 seconds.

    Another option would be to use Future.any, this will race the two futures, if the error report resolves before 2 seconds the timeout will be ignored, else the timeout future will resolve.