Flutter:在调用 super.dispose() 之前必须处理 Ticker

ram*_*man 13 dart flutter

我不知道为什么控制台框中会出现此错误

控制台消息:

SplashScreenState 通过它的 SingleTickerProviderStateMixin 创建了一个 Ticker,但是在 mixin 上调用 dispose() 时,该 Ticker 仍然处于活动状态。在调用 super.dispose() 之前必须处理 Ticker。AnimationControllers 使用的 Tickers 应该通过调用 AnimationController 本身的 dispose() 来处理。否则,代码会泄漏。违规代码是: Ticker(created by SplashScreenState#dae31(lifecycle state: created))

这是我的启动画面完整代码:

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


class SplashScreen extends StatefulWidget {
  @override
  SplashScreenState createState() => new SplashScreenState();
}

class SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  var _visible = true;

  AnimationController animationController;
  Animation<double> animation;

  startTime() async {
    var _duration = new Duration(seconds: 3);
    return new Timer(_duration, navigationPage);
  }

  void navigationPage() {
    Navigator.of(context).pushReplacementNamed(HOME_SCREEN);
  }




  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(seconds: 2),
    );
    animation =
    new CurvedAnimation(parent: animationController, curve: Curves.easeOut);

    animation.addListener(() => this.setState(() {}));
    animationController.forward();

    setState(() {
      _visible = !_visible;
    });
    startTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[

          new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Image.asset(
                'assets/vegan1.png',
                width: animation.value * 280,
                height: animation.value * 280,
              ),
            ],
          ),
        ],
      ),
    );
  }
}


Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误。如果您有解决此问题的任何解决方案或想法,请回答。仅添加重要的点以减少代码的大小。如果您需要更多控制台代码,请发表评论。

Cop*_*oad 46

覆盖dispose方法并处理AnimationController实例。

@override
dispose() {
  animationController.dispose(); // you need this
  super.dispose();
}
Run Code Online (Sandbox Code Playgroud)

  • @CopsOnRoad我想加粗“controller.dispose()”必须在“super.dispose()”之前。 (6认同)
  • 强调位于`super.dispose();`之前 (2认同)