Asyn c метод возвращает ноль в флаттере - PullRequest
0 голосов
/ 26 февраля 2020

Я пытаюсь получить идентификатор проверки из класса APIClient на экране входа в систему.

**In Login.dart**
       FetchVerificationID() {
              ApiProviderObj.FetchFirebaseVeriID().then((value) {
                print(value); // This always get null
              });
            }

В классе APIPROVIDER.dart

Future<String> FetchFirebaseVeriID() async {
    final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
      verificationId = verId;
      return verId; // This is what i am expecting the return value. It take some time to reach here but the method return value before reaching here
    };
    try {
      await _auth.verifyPhoneNumber(
          phoneNumber: '+91 93287 46333', // PHONE NUMBER TO SEND OTP
          codeAutoRetrievalTimeout: (String verId) {
            //Starts the phone number verification process for the given phone number.
            //Either sends an SMS with a 6 digit code to the phone number specified, or sign's the user in and [verificationCompleted] is called.
            verificationId = verId;
          },
          codeSent:
          smsOTPSent, // WHEN CODE SENT THEN WE OPEN DIALOG TO ENTER OTP.
          timeout: const Duration(seconds: 20),
          verificationCompleted: (AuthCredential phoneAuthCredential) {
            print('phoneAuthCredential => ${phoneAuthCredential}');
            return verId;
          },
          verificationFailed: (AuthException exceptio) {
           return "Error";
          });
    } catch (e) {
      return "Error";
    }
  }

Ответы [ 2 ]

1 голос
/ 27 февраля 2020

Я думаю, вы можете попытаться использовать класс Completer, чтобы завершить свое Будущее, когда будет вызван verificationCompleted и verId.

Примерно так:

Future<String> FetchFirebaseVeriID() async {

    // ...

    final completer = new Completer();

    try {
      await _auth.verifyPhoneNumber(

          // ...

          verificationCompleted: (AuthCredential phoneAuthCredential) {
            print('phoneAuthCredential => ${phoneAuthCredential}');
            completer.complete(verId);
          },
          verificationFailed: (AuthException exceptio) {
           completer.completeError("Error");
          });
    } catch (e) {
      completer.completeError("Error");
    }

    return completer.future;
}

https://api.dart.dev/stable/2.7.1/dart-async/Completer-class.html

1 голос
/ 26 февраля 2020

Вы должны иметь оператор return в конце метода.

Я действительно не знаю, что является причиной этого, но у меня была проблема, как у вас с FutureBuilder.

В методе asyn c у меня есть возвращаемые значения, но возвращаемое значение было нулевым.

Future<String> FetchFirebaseVeriID() async {

    String returnVar; //Create return variable

    final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
      verificationId = verId;
      return verId;
    };
    try {
      await _auth.verifyPhoneNumber(
          phoneNumber: '+91 93287 46333', // PHONE NUMBER TO SEND OTP
          codeAutoRetrievalTimeout: (String verId) {
            //Starts the phone number verification process for the given phone number.
            //Either sends an SMS with a 6 digit code to the phone number specified, or sign's the user in and [verificationCompleted] is called.
            verificationId = verId;
          },
          codeSent:
          smsOTPSent, // WHEN CODE SENT THEN WE OPEN DIALOG TO ENTER OTP.
          timeout: const Duration(seconds: 20),
          verificationCompleted: (AuthCredential phoneAuthCredential) {
            print('phoneAuthCredential => ${phoneAuthCredential}');
            returnVar = verId; //Set the return value
          },
          verificationFailed: (AuthException exceptio) {
           returnVar = "Error"; //Set the return value
          });
    } catch (e) {
      returnVar = "Error"; //Set the return value
    }

    return returnVar; //And return the value

  }
...