先上代码

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之后

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐