Home > Net >  Unhandled Exception: This widget has been unmounted, in flutter?
Unhandled Exception: This widget has been unmounted, in flutter?

Time:02-19

I am trying to submit data to the API but throwing a error that the widget is unmounted. Here is the code:

SubmitRequest() async {
    var newValue;
    if(selectedIndex == 0){
      newValue = 2;
    }else if(selectedIndex == 1){
      newValue = 3;
    }else{
      newValue = null;
    }
    var remark;
    if(selectedIndex == 0){
      remark = "Wrong";
    }else if(selectedIndex == 1){
      remark = "Invalid";
    }else{
      return null;
    }
    var url = Uri.parse(url);
    var header = {
      "API-Key": "eeee",
      "Content-Type": "application/json",
    };
    final bdy = jsonEncode({
      "action" :"dhdhd",
      "token":"df23311",
      "date": getCurrentDate().toString(),
      
    });
   
    var jsonresponse = await http.post(url, headers: header, body: bdy);
    print(jsonresponse.statusCode);
    if (jsonresponse.statusCode == 200) {
        Utils.showToastSuccess("Submitted Successfully").show(context);
        print("submit success");
    }else{
      Utils.showToastError("Submit Failed, Try Again").show(context);
    }
  }

when I try to run this the toast will not popup and throws an error:

E/flutter (  615): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter (  615): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
E/flutter (  615): #0      State.context.<anonymous closure> (package:flutter/src/widgets/framework.dart:909:9)
E/flutter (  615): #1      State.context (package:flutter/src/widgets/framework.dart:915:6)
E/flutter (  615): #2      _WrongOrInvalidState.SubmitRequest (package:bmteacher/ui/History/invalid.dart:76:63)
E/flutter (  615): <asynchronous suspension>
E/flutter (  615): 

CodePudding user response:

When you call the method submitRequest(), are you using the keyword await? Because it the method you are trying to use a context that has already been disposed, so probably you app is not waiting the method submitRequest() to finish.

  • Related