skip to Main Content

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
    showDialog(
      context: context,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );

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

      Navigator.pop(context);

      // create user document and send it to api
      createUserData(userCredential.user!.uid);

      // pop loading circle
    } on FirebaseException catch (e) {
      // pop loading circle
      //Navigator.pop(context);

      // 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!");
        Navigator.push(
          context,
          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.

2

Answers


  1. It seems you need pass context from where you call register function and pass it to. createUserData func

    like this

    void register(BuildContext context) async {
        // show loading screen
         createUserData(context);
       }
    
     void createUserData(BuildContext context, String uid) async {
      ...
      ...
       }
    
    Login or Signup to reply.
  2. Try the following solution:

    void register() async {
        // show loading screen
        showDialog(
          context: context,
          builder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
        );
    
        // try create the user
        final result = await createUser();
      
      
        displayNotification(context, result.values.first);
      
        Navigator.pop(context);
      
        if(result.keys.first) {
          Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const LoginOrRegister()),
            );
        }
      
       
      }
    
      Future<Map<bool, String>> createUser() async {
        try {
          UserCredential? userCredential = await FirebaseAuth.instance
              .createUserWithEmailAndPassword(
                  email: _emailController.text, password: _passwordController.text);
          
          final uid = userCredential.user!.uid
          
          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) {
            
            return {true : "Your account was created successfully!"};
            
          } 
          return {false : "Error!"};
        } on FirebaseException catch (e) {
          return {false : "${e.code}"};
        } on DioException catch (e) {
          print("Create Account ERROR ->  ${e.message}");
          return {false : e.message};
        }
      }
    

    Happy Coding

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search