Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter error: setState() called after dispose()

Tags:

flutter

dart

I wrote code to fetch data every 60 seconds and display on the screen. When app launched it shows errors in debug console. Code working fine, gets data every 60 sec and shows on the screen.

Error:

E/flutter ( 2021): #6 _CustomZone.bindUnaryCallbackGuarded. (dart:async/zone.dart:1207:26) E/flutter ( 2021): #7 _rootRunUnary (dart:async/zone.dart:1370:13) E/flutter ( 2021): #8 _CustomZone.runUnary (dart:async/zone.dart:1265:19) E/flutter ( 2021): #9 _CustomZone.bindUnaryCallback. (dart:async/zone.dart:1191:26) E/flutter ( 2021): #10 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19) E/flutter ( 2021): #11 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5) E/flutter ( 2021): #12 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12) E/flutter ( 2021): E/flutter ( 2021): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: setState() called after dispose(): _EvrokoVipScreenState#98462(lifecycle state: defunct, not mounted) E/flutter ( 2021): 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 ( 2021): 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 ( 2021): 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().

  void initState() {
    // TODO: implement initState
    super.initState();
    if (mounted) {
      fetchDataVip();
      new Timer.periodic(Duration(seconds: 60), (Timer t) => setState(() {}));
    }
  }
like image 202
Чак Джонс Avatar asked Aug 29 '26 13:08

Чак Джонс


1 Answers

I think you should dispose of the timer after using it. It should be something like this.

late var timer;
void initState() {
// TODO: implement initState
super.initState();
if (mounted) {
  fetchDataVip();
  timer = new Timer.periodic(Duration(seconds: 60), (Timer t) => setState(() {}));
}
}
  
@override
void dispose() {
  timer.cancel();
  super.dispose();
}
like image 111
Reda Benchraa Avatar answered Aug 31 '26 08:08

Reda Benchraa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!