Error: “This widget has been unmounted, so the State no longer has a context.”

  Kiến thức lập trình

I get an error when I try to send data through a http request using Dio.

This is the code:

  void register() async {
    // show loading screen
      context: context,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),

    // try create the user
    try {
      UserCredential? userCredential = await FirebaseAuth.instance
              email: _emailController.text, password: _passwordController.text);


      // create user document and send it to api

      // pop loading circle
    } on FirebaseException catch (e) {
      // pop loading circle

      // display error message to user
      displayNotification(context, e.code);

  void createUserData(String uid) async {
    try {
      var data = {
        "userId": uid,
        "clientName": _firstNameController.text.toString(),
        "email": _emailController.text.toString(),

      Response response =
          await Dio().post(createAccountEndpoint, data: jsonEncode(data));

      if (response.statusCode == 200) {
        // display error message
        displayNotification(context, "Your account was created successfully!");
          MaterialPageRoute(builder: (context) => const LoginOrRegister()),
      } else {
        displayNotification(context, "Error!");
    } on DioException catch (e) {
      print("Create Account ERROR ->  ${e.message}");

I got the following error when I enter in “createUserData(userCredential.user!.uid);”:

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

I’ve tried to comment that line and it works, but does not send the request.
I’ve tried to use Navigator.pop() and remove all of them, but still not working.

New contributor

André is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.