Flutter call Navigator.pop inside async function

Viewed 1876

I have an async function that gets called when a button is pressed. this function does an http put request, if the result is a success i need to pop to the previous screen.

void updateSurv() async{

  http.Response result;
  result = await http.put(
    "http://10.0.2.2:8000/emergencies/${widget.id}/put",
    body: {

      "title" : titleController.text,
      "Content" : contentController.text,

    }
  );

  if(json.decode(result.body)["result"] == "Success"){

    print("success");
    Navigator.of(context).pop();

  }

}

The value on the server gets updated, the print("success"), but the the app doesn't pop to the previous screen.

so my question is, doesn't the Navigator class work when called from async functions ?

1 Answers

You have to use .then() function to execute such operations.

updateSurv().then((result) {
  if (json.decode(result.body)["result"] == "Success") {
    print("success");
    Navigator.of(context).pop();
  }
});

Future<dynamic> updateSurv() async {
  try {
    result = await http.put("http://10.0.2.2:8000/emergencies/${widget.id}/put", body: {
      "title": titleController.text,
      "Content": contentController.text,
    });

    return result;
  } catch (e) {
    throw e;
  }
}
Related