51

I call my stateful widget page and get some info from the server. If no info found it warns the user that there isn't any info. From the drawer back button, I go back to the previous page. If I keep repeat back and forth very fast I get an error on console message in my IntelliJ IDE as;

E/flutter (22681): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter (22681): setState() called after dispose(): _BillsPayWaterState#66be5(lifecycle state: defunct, not mounted)
E/flutter (22681): 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 of the () 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 (22681): 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 of ().
E/flutter (22681): #0      State.setState.<anonymous closure> 

In my statefull widget I have @override void initState() and I also have @override void dispose()

My question is when I use the drawer back button, How can I dispose of my Stateful Widget completely?

This is the call for widget

onTap: () {
Navigator.push(
  context,
  SlideRightRoute(widget: new BillsWaterPay(“S02")),
);
}

And this the BillsWaterPay widget

List<List<dynamic>> _userAskBills;

// TODO: KURUM KODU - SABIT TELEFON
String _kurumKodu = "";
String _noDataText = "";

class BillsWaterPay extends StatefulWidget {
  final String title;

  BillsWaterPay(this.title);

  @override
  _BillsWaterPayState createState() =>
      _BillsWaterPayState();
}

class _BillsWaterPayState extends State<BillsWaterPay> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _kurumKodu = widget.title;
    _userAskBills;
    _noDataText;
    _loadEverything();
}

Future _loadEverything() async {
    await _getDataFromServer();
}

Future _getDataFromServer() async() {
    …
    …
    if no data
        setState
            _noDataText = “No Data”;  // In here I get an error setState called after dispose

}


@override
void dispose() {
  super.dispose();
      _kurumKodu = widget.title;
    _userAskBills;
    _noDataText;
}
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
Nick
  • 4,163
  • 13
  • 38
  • 63
  • We would need to see the code of your widget. If you register event handlers, you need to unregister them individually. There is no explicit way to dispose your widget, you can just prepare it so Dart can dispose of it. – Günter Zöchbauer Sep 12 '18 at 06:19
  • @Günter I update my question. Look at the Future _getDataFromServer() async() line that I get an error. – Nick Sep 12 '18 at 07:03
  • there's an [ongoing discussion regarding this on github](https://github.com/flutter/flutter/issues/40940). Please voice your support if you think it should be fixed in flutter – morgwai May 31 '21 at 19:56

3 Answers3

115

I assume the problem is caused by the response from the server arrives after the widget is disposed.

Check if the widget is mounted before you call setState. This should prevent the error you are seeing:

// Before calling setState check if the state is mounted. 
if (mounted) { 
  setState (() => _noDataText = 'No Data');
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • thanks, what is it mean if(mounted)? if mounted true or false how should I act? In new BillsWaterPay(“S02") the "S02" always will be different and each different parameter I have to get different result. How mounted will help me for this? – Nick Sep 12 '18 at 07:13
  • 1
    If `mounted` is `false` don't call `setState`. It means the widget is not part of the rendered tree. – Günter Zöchbauer Sep 12 '18 at 07:15
  • thanks. When I call SlideRightRoute(widget: new BillsWaterPay(“S02")), am I not creating a new widget? and void dispose() I assume that I dispose the old widget. So how come, widget is not part of the rendered tree? where I can get detail info for this? – Nick Sep 12 '18 at 07:23
  • 1
    I didn't say it is never part of the rendered tree, just that not when the response from the server arrives. At this point your code might have already created a new instance perhaps from a `setState` on a parent widget (mostly speculation and general info because your question doesn't provide much details). This is why it is usually a bad idea to make server requests from within widgets. At least the response should be cached outside the widgets so that when the same data is requested it's actually used from the cache and not fetched from the server again. – Günter Zöchbauer Sep 12 '18 at 07:28
  • You should use FutureBuilder instead of handling everything yourself. FutureBuilder takes care of all that – Rémi Rousselet Sep 12 '18 at 10:32
  • @RémiRousselet How does FutureBuilder actually handle this? For example, while a FutureBuilder is 'waiting' for a server response, the widget or its parent can still be disposed and thus is not in the widget tree when the network response completes. Then get the same error. – mikeyman22 Jul 14 '20 at 07:53
13

The above exception is shown when we call setState() after we dispose of the widget due to async.

Handle this by using the property of flutter => mounted

mounted tells about the availability of the widget.

...
if (mounted) {
    setState(() {
        ...
    });
}
...
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Anchit Gangrade
  • 179
  • 1
  • 4
0

check if the widget is mounted

@override
  void setState(VoidCallback fn) {
    if (mounted) {
      super.setState(fn);
    }
  }