setState() called after dispose()

后端 未结 6 1898
迷失自我
迷失自我 2020-12-24 04:35

When I click the raised button, the timepicker is showing up. Now if I wait like 5 seconds and then confirm the time this error will occur setState() called after d

相关标签:
6条回答
  • 2020-12-24 04:50

    I had the same problem and i solved changing the super constructor call order on initState():

    Wrong code:

    @override
      void initState() {
        foo_bar(); // in foo_bar i call setState();
        super.initState(); // state initialization after foo_bar()
      }
    

    Right code:

    @override
      void initState() {
        super.initState();
        foo_bar(); // first call super constructor then foo_bar that contains setState() call
      }
    
    0 讨论(0)
  • 2020-12-24 04:51

    If it is an expected behavior that the Future completes when the widget already got disposed you can use

    if (mounted) {
      setState(() {
        selectedDate = new DateTime(selectedDate.year, selectedDate.month, selectedDate.day, picked.hour, picked.minute);
      });
    }
    
    0 讨论(0)
  • 2020-12-24 04:53

    Just check boolean property mounted of the state class of your widget before calling setState().

    if (this.mounted) {
      setState(() {
        // Your state change code goes here
      });
    }
    

    Or even more clean approach Override setState method in your StatelfulWidget class.

    class DateTimeButton extends StatefulWidget {
      @override
      void setState(fn) {
        if(mounted) {
          super.setState(fn);
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-24 05:02

    Try this

    Widget build(BuildContext context) {
        return new RaisedButton(
            child: new Text("${selectedDate.hour} ${selectedDate.minute}"),
            onPressed: () async {
                await initTimePicker();
            }
        );
    }
    
    0 讨论(0)
  • 2020-12-24 05:08

    Just write one line before setState()

     if (!mounted) return;
    

    and then

    setState(() {
          //Your code
        });
    
    0 讨论(0)
  • 2020-12-24 05:10

    mounted

    // First Update data 
    
    if (!mounted) { 
          return;
     }
    setState(() { }
    
    0 讨论(0)
提交回复
热议问题