E/flutter ( 4976): 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.
E/flutter ( 4976): 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.
E/flutter ( 4976): 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 之前对 mounted 进行判断即可
if (mounted) { setState(() { //.... }) }
mounted:此[State]对象当前是否在树中。在创建[State]对象之后,在调用[initState]之前,框架通过将其与[BuildContext]关联来“装入” [State]对象。在框架调用[dispose]之前,[State]对象将保持挂载状态,在此之后,框架将不再要求[State]对象再次进行[build]。除非[mount]为true,否则调用[setState]是错误的。
意思就是在 dispose 之后,不能调用 setState 对象,会造成内存泄漏