Flutter报setState() called after dispose()错误

谁践踏了优雅 2023-10-04 09:15 114阅读 0赞

1.问题描述:

软键盘输入监听动态计算高度中设置setState的调用导致这个问题。

2.问题分析:

State 对象被从对象数卸载释放之后再次调用 setState 就会报 setState() called after dispose()。

3.解决方案:

State 的 mounted 源码:

  1. /// Whether this [State] object is currently in a tree.
  2. ///
  3. /// After creating a [State] object and before calling [initState], the
  4. /// framework "mounts" the [State] object by associating it with a
  5. /// [BuildContext]. The [State] object remains mounted until the framework
  6. /// calls [dispose], after which time the framework will never ask the [State]
  7. /// object to [build] again.
  8. ///
  9. /// It is an error to call [setState] unless [mounted] is true.
  10. bool get mounted => _element != null;

注释中说得很清楚:判断 State 对象现在还在不在对象树中。

So,解决方案就是在 setState 之前先判断一下该 State 是否已经被释放:

  1. if (mounted) {
  2. setState(() {
  3. //具体的操作
  4. });
  5. }

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读