关于flutter中dispose的一些问题

先上代码

import 'package:flutter/material.dart';

import '../../common/view/top_view.dart';

// ignore: must_be_immutable

class StudyDouBanPersonCenterPage extends StatefulWidget {
  const StudyDouBanPersonCenterPage({Key? key}) : super(key: key);

  @override
  State<StudyDouBanPersonCenterPage> createState() =>
      _StudyDouBanPersonCenterPageState();
}

class _StudyDouBanPersonCenterPageState
    extends State<StudyDouBanPersonCenterPage>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  @override
  void initState() {
    super.initState();

    controller =
        AnimationController(vsync: this, duration: Duration(seconds: 2));

    animation = Tween(begin: 250.0, end: 300.0).animate(controller)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          controller.forward();
        }
        setState(() {

        });
      });

    controller.forward(from: 200.0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Image.asset(
            'assets/common/bg_person_center_default.webp',
            width: animation.value,
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    ///特殊说明,Ticker的销毁必须放在super.dispose()之前,
    ///否则,退出当前页面以后,动画的监听和setState还在刷新页面,但是页面已经先销毁了
    controller.dispose();
    super.dispose();
  }
}

遇到的报错

1.

controller.dispose();写在super之后,然后退出页面

The following assertion was thrown while notifying listeners for AnimationController:
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4397 pos 12: '_lifecycleState != _ElementLifecycle.defunct': is not true.


Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.

2.

controller.dispose();写在super之后
// ..addListener(() {
//   setState(() {});
// })屏蔽上述代码

然后退出页面

The following assertion was thrown while finalizing the widget tree:
_StudyDouBanPersonCenterPageState#af77b(ticker active) was disposed with an active Ticker.

_StudyDouBanPersonCenterPageState created a Ticker via its SingleTickerProviderStateMixin, but at the time dispose() was called on the mixin, that Ticker was still active. The Ticker must be disposed before calling super.dispose().

上述报错都是因为controller.dispose();写在super之后

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值