1

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): 
2
  • where did you initialize the context variable? Commented Feb 18, 2022 at 13:25
  • 1
    When widget is removed from the tree, you cannot use its context. You can use GlobalKey to get the context of a widget that you sure exists in the tree and use it. Commented Feb 18, 2022 at 14:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.