【问题标题】:Dispose not working when used with Timer in Dart / Flutter在 Dart / Flutter 中与 Timer 一起使用时 Dispose 不起作用
【发布时间】:2021-12-15 13:27:24
【问题描述】:

我怎样才能让它工作?

 @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

这就是我所拥有的:

class _ListCell extends State<ListCell> {
  @override
  void initState() {
    super.initState();
    Timer timer = Timer.periodic(Duration(seconds: 1), (_) => ListCell());
  }

不断收到错误:

 Error: The getter 'timer' isn't defined for the class '_ListCell'.

【问题讨论】:

    标签: json flutter api dart


    【解决方案1】:

    您收到错误是因为计时器变量的定义超出了dispose 方法的范围。这是因为您在initState 方法中定义了变量。

    解决方案:

    timer 变量的定义移到initState 方法之外,如下所示:

    class _ListCell extends State<ListCell> {
      Timer? timer;
    
      @override
      void initState() {
        super.initState();
        timer = Timer.periodic(Duration(seconds: 1), (_) => ListCell());
      }
      
      ...
    

    由于 timer 变量现在可以为空,因为它的类型为 Timer?,因此您需要在 dispose 方法中对其使用空检查运算符。

     @override
      void dispose() {
        timer?.cancel();
        super.dispose();
      }
    

    结帐 Dart 的 Lexical Scope

    【讨论】:

    • 使用Timer? timer;。我已经编辑了我的答案。
    • 完美,非常感谢!
    • PS:timer?.cancel 和 timer!.cancel 有什么区别?
    • 哦。我的意思是写timer?.cancel。不同之处在于timer?.cancel() 意味着cancel() 方法仅在timer 不为空时运行,而timer!.cancel() 意味着cancel() 方法无论如何都会运行,因此当您完全确定变量不为空。
    • 谢谢,维克多!感谢您的帮助。
    猜你喜欢
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2022-01-25
    • 2022-01-05
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    相关资源
    最近更新 更多