FlutterFire验证PhoneNumber方法未被等待

g6baxovj  于 2023-01-31  发布在  Flutter
关注(0)|答案(2)|浏览(145)

我正在尝试创建一个auth服务,我想从自定义方法返回verificationId,但是调用这个方法会抛出null检查异常,因为它没有等到Future完成后再返回。

Future<String> sendPhoneVerification({
    required String phoneNumber,
  }) async {
    String? result;
    await FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: '+1$phoneNumber',
      verificationCompleted: (
        PhoneAuthCredential credential,
      ) {
        result = credential.verificationId;
      },
      verificationFailed: (e) {
        if (e.code == 'invalid-phone-number') {
          throw InvalidPhoneNumberAuthException();
        } else if (e.code == 'too-many-requests') {
          throw TooManyRequestsAuthException();
        } else {
          throw GenericAuthException();
        }
      },
      codeSent: (verificationId, resendToken) {
        print('ver_id $verificationId');
        result = verificationId;
      },
      codeAutoRetrievalTimeout: (_) {},
    );
    print('This is the result $result');
    return result!;
  }

这是终端的输出。

flutter: This is the result null
flutter: ver_id <ver_id>
ujv3wf0j

ujv3wf0j1#

修复此问题的一种方法是将方法 Package 在Future中并返回Future。

Future<String> sendPhoneVerification({
    required String phoneNumber,
  }) {
    return Future.delayed(Duration.zero, () async {
    String? result;
    await FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: '+1$phoneNumber',
      verificationCompleted: (
        PhoneAuthCredential credential,
      ) {
        result = credential.verificationId;
      },
      verificationFailed: (e) {
        if (e.code == 'invalid-phone-number') {
          throw InvalidPhoneNumberAuthException();
        } else if (e.code == 'too-many-requests') {
          throw TooManyRequestsAuthException();
        } else {
          throw GenericAuthException();
        }
      },
      codeSent: (verificationId, resendToken) {
        print('ver_id $verificationId');
        result = verificationId;
      },
      codeAutoRetrievalTimeout: (_) {},
    );
    print('This is the result $result');
    return result!;
    });
  }
oxf4rvwz

oxf4rvwz2#

请在verifyPhoneNumber()方法中添加此属性timeout: const Duration(seconds: 60),

相关问题