timeout method Null safety

  1. @override
Future<T> timeout(
  1. Duration timeLimit,
  2. {FutureOr<T> onTimeout(
      )?}
    )
    override

    Time-out the future computation after timeLimit has passed.

    Returns a new future that completes with the same value as this future, if this future completes in time.

    If this future does not complete before timeLimit has passed, the onTimeout action is executed instead, and its result (whether it returns or throws) is used as the result of the returned future. The onTimeout function must return a T or a Future<T>.

    If onTimeout is omitted, a timeout will cause the returned future to complete with a TimeoutException.

    Example:

    void main() async {
      var result = await waitTask()
          .timeout(const Duration(seconds: 10));
      print(result); // 'completed'
    
      result = await waitTask()
          .timeout(const Duration(seconds: 1), onTimeout: () => 'timeout');
      print(result); // 'timeout'
    
      result = await waitTask()
          .timeout(const Duration(seconds: 2)); // Throws.
    }
    
    Future<String> waitTask() async {
      await Future.delayed(const Duration(seconds: 5));
      return 'completed';
    }
    

    Implementation

    @override
    Future<T> timeout(Duration timeLimit, { FutureOr<T> Function()? onTimeout }) {
      return Future<T>.value(_value).timeout(timeLimit, onTimeout: onTimeout);
    }