1. 문제 상황

 

FlutterError (setState() called after dispose(): _TickerUpdateWidgetState#1a689(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().)
 
FlutterError (setState() called after dispose(): _TickerUpdateWidgetState#1a689(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().)
 

 

아래 소스코드에서 위와 같은 오류 발생하며 앱이 죽어버리는 상황

class EditScreen extends StatefulWidget {


// ...


  @override
  void initState() {
    super.initState();
    widget.priceController.addListener(() {
      setState(() {});
    });
  }
  
  
// ...

 

 

 

 

 

2. 문제 원인

 

mount되어있지 않은 상황에서 setState를 시도해 오류 발생함

 

 

 

 

 

3. 해결방법

 

mount 여부를 확인한 후, mount되어있는 경우에만 setState 진행

 

  @override
  void initState() {
    super.initState();
    widget.priceController.addListener(() {
      if (mounted) setState(() {});
    });
  }

 


@override
void initState() {
    super.initState();
        // price 정보 변경시 view 새로고침
        widget.priceController.addListener(() {
        if (mounted) setState(() {});
    });
}
 

 

 

 

 

+ Recent posts