【问题标题】:Link a phone number to existing firebase account将电话号码关联到现有的 Firebase 帐户
【发布时间】:2021-07-31 16:29:35
【问题描述】:

我正在尝试将电话号码链接到我的颤振应用的现有帐户,以避免垃圾邮件帐户。 步骤: 1.点击注册按钮我运行.verifyPhoneNumber(),它必须返回一个PhoneAuthCredential。然后我进入我的signUp()(未来)函数,创建一个firebase帐户,然后链接我返回的PhoneAuthCredential

但我的问题是当我调用.verifyPhoneNumber() 时,我的注册函数立即被调用,所以我的.verifyPhoneNumber() 返回为空。我不知道如何等待非空返回进入我的signUp() 函数。

这是我点击注册时的电话:

ElevatedButton(
                    onPressed: () {
                      if (_formKey.currentState.validate()) {
                        controller.verifyPhoneNumberThenSignUp(
                            phoneNumberFieldController.text.trim());

                        controller.signUp(
                          firstname: firstnameFieldController.text,
                          lastname: lastnameFieldController.text,
                          email: mailFieldController.text.trim(),
                          countryCode: countryCode,
                          password: passwordFieldController.text,
                          username: usernameFieldController.text.trim(),
                          phoneNumber: phoneNumberFieldController.text.trim(),
                         
                        );
                        firstnameFieldController.clear();
                        lastnameFieldController.clear();
                        mailFieldController.clear();
                        passwordFieldController.clear();
                        usernameFieldController.clear();
                        phoneNumberFieldController.clear();

                        //Get.to(() => MailVerificationPage());
                      }
                    },
                    child: Text("Créer mon compte !"),
                  )

我的 verifyPhoneNumberThenSignUp :

Future<void> verifyPhoneNumberThenSignUp(
    String phoneNumber,
  ) async {
    phoneNumber = "MY NUMBER FOR TESTING";
    try {
      await auth.verifyPhoneNumber(
          timeout: Duration(seconds: 120),
          phoneNumber: phoneNumber,
          // verificationCompleted only gets called when verification is doxne automatically
          verificationCompleted: (AuthCredential credential) async {
            phoneNumberCredential =
                credential; //public variable used to link with mailSignUp account

            Get.back();
          },
          verificationFailed: (FirebaseAuthException exception) {
            print(exception);
          },
          codeSent: (String verificationId, [int forceResendingToken]) {
            final _codeController = TextEditingController();
            Get.dialog(AlertDialog(
              title: Text("Give the code :"),
              content: Column(
                children: [
                  TextField(
                    controller: _codeController,
                  )
                ],
              ),
              actions: [
                CupertinoButton(
                    child: Text("Confirm"),
                    onPressed: () async {
                      AuthCredential credential = PhoneAuthProvider.credential(
                          verificationId: verificationId,
                          smsCode: _codeController.text.trim());

                      UserCredential result =
                          await auth.signInWithCredential(credential);

                      User user = result.user;

                      if (user != null) {
                        //Get.to(NavigationThroughTheApp);
                        print("Verification completed !!");
                        print(user.phoneNumber);
                        Get.back();
                      } else {
                        print("Error on user null safety");
                      }
                    })
              ],
            ));
          },
          codeAutoRetrievalTimeout: (String verificationId) {});
    } catch (e) {
      Get.snackbar("Error", e.message, snackPosition: SnackPosition.BOTTOM);
    }
  }

我的注册:

Future<void> signUp({
    String firstname,
    String lastname,
    String email,
    String countryCode,
    String password,
    String username,
    String phoneNumber,
  }) async {
    //if (await Database().usernameExists(username) != true) {
    //FIREBASE REGISTRATION
    //bool toto =
    //await verifBigo(); //FIXME n attend pas la verif pr continuer donc tjrs false

    // if (toto == false) {
// phone number verified
    try {
      print("checking phone credential not null...");
      if (phoneNumberCredential == null) return;
      print("phone credential not null");
      showLoading();
      //_firebaseAuth.verifyPhoneNumber(phoneNumber: phoneNumber, verificationCompleted: verificationCompleted, verificationFailed: verificationFailed, codeSent: codeSent, codeAutoRetrievalTimeout: codeAutoRetrievalTimeout)
      UserCredential _authResult = await _firebaseAuth
          .createUserWithEmailAndPassword(email: email, password: password);
      print("Try linking phoneNumber to created account");
      user.linkWithCredential(phoneNumberCredential);
      print("phoneNumber linked to created account !!!!! ");
      user.sendEmailVerification();

      UserModel _user = new UserModel(
          id: _authResult.user.uid,
          firstname: firstname,
          lastname: lastname,
          email: _authResult.user.email,
          countryCode: countryCode,
          passwordHash: null,
          username: username,
          phoneNumber: phoneNumber,
          creationDate: Timestamp.fromDate(DateTime.now()));

      if (await Database().createUser(_user)) {
        print("account registred in our DB");
        if (!Get.isRegistered<UserController>()) Get.put(UserController());
        Get.find<UserController>().user = _user;
        Get.back();
      }
      Get.put(PartyController(), permanent: true);
      Get.offAll(() => NavigationThroughTheApp());
      /*} else {
      Get.snackbar(
        "Error creating Account",
        "Username already taken",
        snackPosition: SnackPosition.BOTTOM,
      );
      }*/
      // }
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        print('The password provided is too weak.');
      } else if (e.code == 'email-already-in-use') {
        print('The account already exists for that email.');
      }
    } catch (e) {
      Get.snackbar(
        "Error creating Account",
        e.message,
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }

【问题讨论】:

  • "寻求调试帮助的问题('为什么这段代码不工作?')必须包括期望的行为、特定问题或错误必要的最短代码 在问题本身。没有明确的问题陈述的问题对其他读者没有用处。请参阅:@ 987654321@"
  • 这是我的代码

标签: firebase flutter firebase-authentication


【解决方案1】:

您可以通过将await 关键字放在方法前面并将调用异步方法的函数标记为async 来等待异步方法完成。

您的onPressed 回调应更新为:

onPressed: () async {
  if (_formKey.currentState.validate()) {
    await controller.verifyPhoneNumberThenSignUp(
      phoneNumberFieldController.text.trim());

    await controller.signUp(
      firstname: firstnameFieldController.text,
      lastname: lastnameFieldController.text,
      email: mailFieldController.text.trim(),
      countryCode: countryCode,
      password: passwordFieldController.text,
      username: usernameFieldController.text.trim(),
      phoneNumber: phoneNumberFieldController.text.trim(),
    );

    firstnameFieldController.clear();
    lastnameFieldController.clear();
    mailFieldController.clear();
    passwordFieldController.clear();
    usernameFieldController.clear();
    phoneNumberFieldController.clear();

    //Get.to(() => MailVerificationPage());
   }
 },

【讨论】:

  • 这是我不明白的,我已经尝试过了,但是它不起作用。我现在只是重试以检查这是否不是我自己的错误,但仍然无法正常工作。它会在我的注册功能中立即跳转并填写我的 AuthCredential。
  • 它保持不起作用,我真的不明白这是怎么回事。
猜你喜欢
  • 2021-06-26
  • 1970-01-01
  • 2019-01-11
  • 2019-11-21
  • 2018-03-21
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多