关于快速滑动flutter_staggered_grid_view导致的错误

来源:5-3 揭开Flutter新版导航器和路由系统的面纱

光_cfstOQ

2025-07-16

FlutterError (setState() called after dispose(): _HomeTabPageState#97bfe(lifecycle state: defunct, not mounted)
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the “mounted” property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().)会在setState(() {
if(loadMore){
if(result.videoList!.isNotEmpty){
videoList = […videoList,…result.videoList!];
pageIndex++;
}这个setState这个地方报错 我的感觉是 因为快速滑动页面,导致异步注销的页面被瞬间加载,这里出现了错误,这个情况要怎么解决比较好?

写回答

1回答

CrazyCodeBoy

2025-07-16

在调用的时候判断下mounted,课程后面有讲解,可参考下
https://git.imooc.com/coding-487/fa-component/src/master/component/hi_base/lib/hi_state.dart


import 'package:flutter/material.dart';

///页面状态异常管理

abstract class HiState<T extends StatefulWidget> extends State<T> {

@override

void setState(fn) {

if (mounted) {

super.setState(fn);

} else {

print('HiState:页面已销毁,本次setState不执行:${toString()}');

}

}

}
0
0

Flutter高级进阶实战-仿哔哩哔哩-掌握Flutter高阶技能

一次性掌握Flutter高阶技能+商业级复杂项目架构设计与开发方案

1793 学习 · 900 问题

查看课程