Flutter 报错 setState() called after dispose()

2021-02-02 15:49:11 浏览数 (1)

今天在写一个音乐播放器,遇到一个问题就是在播放界面开始播放后,返回其他界面,就一直报setState() called after dispose() 的错误

其实就是播放器在播放更新进度的时候,当我离开播放页面后其实播放页面已经被dispose了。而此时播放器还一直播放(这里说明一下播放器类是全局。所以离开了播放界面但是播放还是在播放),一直在更新进度条。所以就报setState() called after dispose() 的错误。 解决办法,在setState的时候加上if(mounted)的判断就好了

其他场景也可能遇到,比如网络请求延时了。当我返回上一个页面的时候,此时数据回来了然后在调用setState的时候也会报这样的错误

代码语言:javascript复制
if(mounted){
       setState(() {
           ........
       });
     }
    });

下面是mounted的属性

代码语言:javascript复制
 /// 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]是错误的。

0 人点赞