flutter取消Future.delayed

前言

学习flutter,其中用Futere.delayed延时1s跳转到其他页面的时 如果没跳转前离开当前页面就会报

Future.delayed(const Duration(seconds: 1), () {
  Navigator.of(context).pushNamed("");
});
//报错
This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
    Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.

问题分析

说明其实很清楚了,就是widget已经unmounted 不能跳转,我们需要在dispose取消下Future,所以需要看下delayed的源码:

  factory Future.delayed(Duration duration, [FutureOr<T> computation()?]) {
    _Future<T> result = new _Future<T>();
    new Timer(duration, () {
      if (computation == null) {
        result._complete(null as T);
      } else {
        try {
          result._complete(computation());
        } catch (e, s) {
          _completeWithErrorCallback(result, e, s);
        }
      }
    });
    return result;
  }

发现其实内部用是Timer实现,返回的_Future并找到对应方法取消,干脆直接用Timer实现好了,注意还是需要dispose取消

    _timer = Timer(const Duration(seconds: 1), () {
      Navigator.of(context).pushNamed("");
    });
    
	  @override
	  void dispose() {
	    super.dispose();
	    _timer?.cancel();
	  }

你可能感兴趣的:(Flutter,flutter,android)