简体   繁体   English

在 Dart / Flutter 中与 Timer 一起使用时 Dispose 不起作用

[英]Dispose not working when used with Timer in Dart / Flutter

How can I get it to work?我怎样才能让它工作?

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

And this is what I have:这就是我所拥有的:

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

Constantly getting the error:不断得到错误:

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

You're getting the error because the timer variable is defined out of the scope of the dispose method.您收到错误是因为 timer 变量是在dispose方法的范围之外定义的。 This is because you defined the variable in the initState method.这是因为您在initState方法中定义了变量。

Solution:解决方案:

Move the definition of the timer variable outside the initState method like this:timer变量的定义initState方法之外,如下所示:

class _ListCell extends State<ListCell> {
  Timer? timer;

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

Since the timer variable is now nullable as it is of type Timer?由于timer变量现在可以为空,因为它属于Timer?类型Timer? , you need to use the null-check operator on it in the dispose method. ,您需要在 dispose 方法中对其使用空检查运算符。

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

Checkout Dart's Lexical Scope结帐 Dart 的词法范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM