今天在写一个音乐播放器,遇到一个问题就是在播放界面开始播放后,返回其他界面,就一直报setState() called after dispose() 的错误
其实就是播放器在播放更新进度的时候,当我离开播放页面后其实播放页面已经被dispose了。而此时播放器还一直播放(这里说明一下播放器类是全局。所以离开了播放界面但是播放还是在播放),一直在更新进度条。所以就报setState() called after dispose() 的错误。 解决办法,在setState的时候加上if(mounted)的判断就好了
其他场景也可能遇到,比如网络请求延时了。当我返回上一个页面的时候,此时数据回来了然后在调用setState的时候也会报这样的错误
if(mounted){
setState(() {
........
});
}
});
下面是mounted的属性
/// Whether this [State] object is currently in a tree.
///
/// After creating a [State] object and before calling [initState], the
/// framework "mounts" the [State] object by associating it with a
/// [BuildContext]. The [State] object remains mounted until the framework
/// calls [dispose], after which time the framework will never ask the [State]
/// object to [build] again.
///
/// It is an error to call [setState] unless [mounted] is true.
bool get mounted => _element != null;
最后一句已经说明白了///除非[mount]为true,否则调用[setState]是错误的。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有