Home > other >  Is it possible to cancel a function call after it has been called?
Is it possible to cancel a function call after it has been called?

Time:08-28

In my case, the user adds his phone number to get an OTp code from Firebase. After he called the send me OTP function, he decided to edit his phone number, so he pressed the device back button and edited his phone number, and then he pressed the send me OTP function again. What happened is that he may have gotten two SMSs if the previous phone is correct, because he called the function two times. or The previous Otp code may go to some one phone number. I don't want to send Otp two times or to an unknown phone number by mistake.

Here my code to send Otp from Firebase.

  _verifyPhone() async {
    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: '${widget.phone}',
        verificationCompleted: (PhoneAuthCredential credential) async {
          await FirebaseAuth.instance
              .signInWithCredential(credential)
              .then((value) async {
            if (value.user != null) {
              Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(builder: (context) => Tabs(widget.phone)),
                  (route) => false);
            }
          });
        },
        verificationFailed: (FirebaseAuthException e) {
          Get.snackbar(
             "something went wrong", "try again latter or Resend SMS",
            duration:Duration(seconds: 8),
           
            );
            setState(() {
              _start=0;
            });
            startTimer();
             
        },
        codeSent: (String? verficationID, int? resendToken) {
          setState(() {
            _verificationCode = verficationID;
            _resendToken = resendToken;
          });
        },
        codeAutoRetrievalTimeout: (String verificationID) {
          setState(() {
            _verificationCode = verificationID;
          });
        },
        timeout: const Duration(seconds: 60));
    _resendToken;
  }

CodePudding user response:

You can map your future to a Stream

_verifiyPhone().asStream().listen((result){});

Save the StreamSubscription in a variable

StreamSubscription subscription = _verifiyPhone().asStream().listen((result){});

And cancel it if you press the back button. For this you have to call the cancel Method

subscription.cancel()
  • Related