在Timer内部调用setState会导致Flutter内存泄露?

Calling setState inside the Timer will cause memory leak in Flutter?

我正在开发一个 flutter 应用程序。在此应用程序中,我在计时器内调用 setState()。我在 initState() 内启动了定时器。我在下面附上了我的代码,这段代码会导致内存泄漏吗?谢谢

import 'dart:async';
import 'package:androidtv/Utils/StringConstants.dart';
import 'package:androidtv/Utils/TimerConstants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_analog_clock/flutter_analog_clock.dart';

class CustomAnalogClock extends StatefulWidget {
  final DateTime countryTime;

  const CustomAnalogClock({Key key, this.countryTime}) : super(key: key);
  @override
  _CustomAnalogClockState createState() => _CustomAnalogClockState(countryTime);
}

class _CustomAnalogClockState extends State<CustomAnalogClock> {
  DateTime countryTime;
  _CustomAnalogClockState(this.countryTime);

  Timer timer;

  @override
  void initState() {
    timer = Timer.periodic(Duration(seconds: TimerConstants.ANALOG_CLOCK_TIMER), (Timer t) => setupWorldTime());
    super.initState();
  }

  setupWorldTime() {
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return FlutterAnalogClock(
      dateTime: countryTime,
      hourHandColor: Colors.black,
      minuteHandColor: Colors.black,
      secondHandColor: Colors.red,
      numberColor: Colors.black,
      tickColor: Colors.black,
      centerPointColor: Colors.black,
      showMinuteHand: true,
      showSecondHand: true,
      showNumber: true,
      borderWidth: 0.5,
      showTicks: true,
      hourNumberScale: 1.40,
      hourNumbers: [
        StringConstants.CLOCK_NO_01,
        StringConstants.CLOCK_NO_02,
        StringConstants.CLOCK_NO_03,
        StringConstants.CLOCK_NO_04,
        StringConstants.CLOCK_NO_05,
        StringConstants.CLOCK_NO_06,
        StringConstants.CLOCK_NO_07,
        StringConstants.CLOCK_NO_08,
        StringConstants.CLOCK_NO_09,
        StringConstants.CLOCK_NO_10,
        StringConstants.CLOCK_NO_11,
        StringConstants.CLOCK_NO_12
      ],
      isLive: true,
      decoration: BoxDecoration(
          border: Border.all(width: 2.0, color: Colors.black),
          color: Colors.transparent,
          shape: BoxShape.circle),
    );
  }
}

我之前遇到过同样的问题,您的代码不会遇到内存泄漏问题,因为您正在取消 dispose() 方法中的周期性计时器。

但是你的代码不应该 运行 在 flutter 2 中。也正如@pskink 提到的 FlutterAnalogClock

里面可能有问题
late Timer timer;

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

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