flutterdartlifecyclepage-lifecycle

Error - Unhandled Exception: This widget has been unmounted, so the State no longer has a context


i call the data i get from the service in didChangeDependencies to reflect it on the page. Because when i call this in initState, i'm facing an error. Anyway, this is not my main problem. My main problem is when page loaded, i got datas but when i want to go previous page, im facing a problem :
"Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct)." "Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active." According to my research, i should use "mounted" in if state. But it didn't work. Also i tried if statement like this:

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

These are errors i got

My code:

List<DetailObjects?> onOdemeDetay = [];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    OnOdemeListeClass().fetchList(context).then((value) {
      final checkData = Provider.of<LoginInfo>(context, listen: false);
      if (mounted) {
        setState(() {
          if (value != null && value.detailObjects != null) {
            onOdemeDetay = value.detailObjects!;
            checkData.updateLabel(onOdemeDetay[0]?.label);
            checkData.updateValue(onOdemeDetay[0]?.value);
          }
        });
      }
    });
  }

Solution

  • If you want to update the state before going to previous page, you have to add delay of 2 seconds, which means when user press back button, firstly state will be update and then user will navigate to previous page.

     onPressed: () {
    
      //First Update your state here
    
      Future.delayed(Duration(seconds: 2)).then((value) {
         //Code to navigate previous page
      });
    },