当前位置: 首页 > 知识库问答 >
问题:

Flatter中的Firebase电话认证

曾皓
2023-03-14

我遵循了Flatter fire文档来实现firebase phone auth。我在firebase_auth(firebase_auth:0.14.0 5)的早期版本中尝试了这一点,一切似乎都正常,但我启动了一个新的应用程序,并安装了最新版本的firebase_auth(firebase_auth:0.18.1 2),每当我调用firebase verifyNumber方法时,我的应用程序都会显示以下日志:

E/zza     (12630): Problem retrieving SafetyNet Token: 7: 
D/ViewRootImpl@bab4cc4[MainActivity](12630): MSG_WINDOW_FOCUS_CHANGED 0
W/zzdq    (12630): keyset not found, will generate a new one
W/zzdq    (12630): java.io.FileNotFoundException: can't read keyset; the pref value GenericIdpKeyset does not exist
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdv.zzc(com.google.firebase:firebase-auth@@20.0.0:13)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdv.zzb(com.google.firebase:firebase-auth@@20.0.0:32)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzbd.zza(com.google.firebase:firebase-auth@@20.0.0:8)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdq$zza.zzd(com.google.firebase:firebase-auth@@20.0.0:73)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdq$zza.zzc(com.google.firebase:firebase-auth@@20.0.0:60)
W/zzdq    (12630):  at com.google.android.gms.internal.firebase-auth-api.zzdq$zza.zza(com.google.firebase:firebase-auth@@20.0.0:27)
W/zzdq    (12630):  at com.google.firebase.auth.internal.zzi.<init>(com.google.firebase:firebase-auth@@20.0.0:9)
W/zzdq    (12630):  at com.google.firebase.auth.internal.zzi.zza(com.google.firebase:firebase-auth@@20.0.0:17)
W/zzdq    (12630):  at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth@@20.0.0:116)
W/zzdq    (12630):  at com.google.firebase.auth.api.internal.zzeq.<init>(com.google.firebase:firebase-auth@@20.0.0:14)
W/zzdq    (12630):  at com.google.firebase.auth.internal.RecaptchaActivity.onResume(com.google.firebase:firebase-auth@@20.0.0:78)
W/zzdq    (12630):  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1277)
W/zzdq    (12630):  at android.app.Activity.performResume(Activity.java:7088)
W/zzdq    (12630):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3768)
W/zzdq    (12630):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3832)
W/zzdq    (12630):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2994)
W/zzdq    (12630):  at android.app.ActivityThread.-wrap14(ActivityThread.java)
W/zzdq    (12630):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
W/zzdq    (12630):  at android.os.Handler.dispatchMessage(Handler.java:102)
W/zzdq    (12630):  at android.os.Looper.loop(Looper.java:154)
W/zzdq    (12630):  at android.app.ActivityThread.main(ActivityThread.java:6682)
W/zzdq    (12630):  at java.lang.reflect.Method.invoke(Native Method)
W/zzdq    (12630):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
W/zzdq    (12630):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
I/zzip    (12630): Provider GmsCore_OpenSSL not available
I/System.out(12630): (HTTPLog)-Static: isSBSettingEnabled false
I/System.out(12630): (HTTPLog)-Static: isSBSettingEnabled false
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): ThreadedRenderer.create() translucent=true
D/InputTransport(12630): Input channel constructed: fd=95
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): setView = DecorView@7954fc2[RecaptchaActivity] touchMode=true
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): dispatchAttachedToWindow
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1440,2560] result=0x27 surface={isValid=true 501132826624} surfaceGenerationChanged=true
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): mHardwareRenderer.initialize() mSurface={isValid=true 501132826624} hwInitialized=true
D/mali_winsys(12630): EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1440x2560]-format:1
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): MSG_WINDOW_FOCUS_CHANGED 1
D/ViewRootImpl@9c9340d[RecaptchaActivity](12630): mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 501132826624}
V/InputMethodManager(12630): Starting input: tba=android.view.inputmethod.EditorInfo@46ca60e nm : com.example.harpy ic=null
I/InputMethodManager(12630): [IMM] startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(12630): Input channel constructed: fd=101
D/InputTransport(12630): Input channel destroyed: fd=93
W/IInputConnectionWrapper(12630): finishComposingText on inactive InputConnection
D/AndroidRuntime(12630): Shutting down VM
E/AndroidRuntime(12630): FATAL EXCEPTION: main
E/AndroidRuntime(12630): Process: com.example.harpy, PID: 12630
E/AndroidRuntime(12630): java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/browser/customtabs/CustomTabsIntent$Builder;
E/AndroidRuntime(12630):    at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth@@20.0.0:92)
E/AndroidRuntime(12630):    at com.google.firebase.auth.api.internal.zzeq.zza(com.google.firebase:firebase-auth@@20.0.0:79)
E/AndroidRuntime(12630):    at com.google.firebase.auth.api.internal.zzeq.onPostExecute(com.google.firebase:firebase-auth@@20.0.0:88)
E/AndroidRuntime(12630):    at android.os.AsyncTask.finish(AsyncTask.java:660)
E/AndroidRuntime(12630):    at android.os.AsyncTask.-wrap1(AsyncTask.java)
E/AndroidRuntime(12630):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
E/AndroidRuntime(12630):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(12630):    at android.os.Looper.loop(Looper.java:154)
E/AndroidRuntime(12630):    at android.app.ActivityThread.main(ActivityThread.java:6682)
E/AndroidRuntime(12630):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12630):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
E/AndroidRuntime(12630):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
E/AndroidRuntime(12630): Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.browser.customtabs.CustomTabsIntent$Builder" on path: DexPathList[[zip file "/data/app/com.example.harpy-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.harpy-1/lib/arm64, /data/app/com.example.harpy-1/base.apk!/lib/arm64-v8a, /system/lib64, /vendor/lib64]]
E/AndroidRuntime(12630):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E/AndroidRuntime(12630):    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
E/AndroidRuntime(12630):    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(12630):    ... 12 more
Lost connection to device.

我的应用程序崩溃的原因可能是什么?

注意:我没有收到短信

共有3个答案

霍建柏
2023-03-14

兄弟,我也面临着同样的问题,我自己能找到的唯一答案是,在我的案例中,使用早期版本是firebase_auth 19.3.2,最新版本有一些小错误。所以先用一个直到现在。

贲宜春
2023-03-14

这是对我有用的代码

import 'dart:async';

import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:harpy/providers/AuthenticationProvider.provider.dart';
import 'package:harpy/services/AuthRoute.service.dart';
import 'package:harpy/types/Response.type.dart';
import 'package:provider/provider.dart';

class AuthService{
  FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final HttpsCallable createUser = CloudFunctions.instance.getHttpsCallable(functionName: 'createUser');
  String verificationId;
  AuthRoute _authRoute = AuthRoute();


  Future<void> validatePhoneNumberWithOTP(BuildContext context, String code) async{
    Provider.of<AuthenticationProvider>(context, listen: false).loading = true;
    // final AuthCredential authCredential = PhoneAuthProvider.getCredential(verificationId: this.verificationId, smsCode: code);
    final AuthCredential authCredential = PhoneAuthProvider.credential(verificationId: this.verificationId, smsCode: code);

    // final AuthResult _userCredential = await _firebaseAuth.signInWithCredential(authCredential);
    final UserCredential _userCredential = await _firebaseAuth.signInWithCredential(authCredential);
    Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
    if(_userCredential.user != null){
      Provider.of<AuthenticationProvider>(context, listen: false).userIsVerified = true;
      //route here
    }else{
      Provider.of<AuthenticationProvider>(context, listen: false).userIsVerified = false;
      //TODO: show snackbar
      print("Enter the correct PIN");
    }

  }

  initAuth({BuildContext context, String phoneNumber}) async {
    Provider.of<AuthenticationProvider>(context, listen: false).loading = true;

    final PhoneVerificationCompleted verificationCompleted = (AuthCredential phoneAuthCredential) async {
      Provider.of<AuthenticationProvider>(context, listen: false).loading = true;
      // final AuthResult authResult = await _firebaseAuth.signInWithCredential(phoneAuthCredential);
      final UserCredential authResult = await _firebaseAuth.signInWithCredential(phoneAuthCredential);
      if(authResult.user != null){
        Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
        Provider.of<AuthenticationProvider>(context, listen: false).userIsVerified = true;
      }
    };

    // final PhoneVerificationFailed verificationFailed = (AuthException authException) {
    final PhoneVerificationFailed verificationFailed = (FirebaseAuthException authException) {
      //TODO: handle verification failed exceptions
      print('Auth Exception is ${authException.message}');
    };

    final PhoneCodeSent codeSent = (String verificationId, [int forceResendingToken]) async {
      Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
      Provider.of<AuthenticationProvider>(context, listen: false).codeSent = true;
      this.verificationId = verificationId;
    };

    final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout = (String verificationId) {
      //TODO: handle timeouts
      this.verificationId = verificationId;
    };

    await _firebaseAuth.verifyPhoneNumber(
        phoneNumber: phoneNumber,
        verificationCompleted: verificationCompleted,
        verificationFailed: verificationFailed,
        codeSent: codeSent,
        codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
        timeout: Duration(seconds: 60)
    );

  }

  Future<Response> updateUserprofile({context, String name,String email}) async{

    User _user = _firebaseAuth.currentUser;
    Response response = Response(success: false);
    Provider.of<AuthenticationProvider>(context, listen: false).loading = true;

    try{

      HttpsCallableResult functionResponse  = await createUser.call({'displayName': name, 'email':email, 'phoneNumber': _user.phoneNumber});
      response.success = functionResponse.data['success'];
      response.message = functionResponse.data['message'];

      _user.updateProfile(displayName: name);
      // _user.updateEmail(email);

      AuthCredential credential = AuthCredential(providerId: PhoneAuthProvider.PROVIDER_ID, signInMethod: PhoneAuthProvider.PHONE_SIGN_IN_METHOD);
      await _user.reauthenticateWithCredential(credential);

      _user.reload();

      Provider.of<AuthenticationProvider>(context, listen: false).loading = false;

      return response;
    }catch(e){
      Provider.of<AuthenticationProvider>(context, listen: false).loading = false;
      response.message = e.message;
      return response;
    }
  }

  signOut(BuildContext context) async{
    await _firebaseAuth.signOut();
    _authRoute.route(context);
  }
}

卢雅惠
2023-03-14

我得到了同样的问题,并通过更新最新包装的flutter和android解决了它,我添加了SHA-1和SHA-256,并仅使用flutter留档方法,然后它开始正常工作

 类似资料:
  • 我试图用手机登录。每次我输入手机号码时,它都会显示这些错误消息并退出应用程序。我使用了https://firebase.flutter.dev/docs/auth/phone留档中的代码。代码几乎与留档相同。 我正在为Java/Flatter/Firebase sdk等所有东西使用更新版本。我还在Firebase应用程序中添加了SHA1密钥,并启用了手机认证。我还尝试了物理和虚拟设备。但每次都是同

  • 我是一个新的flutter,并使用firebase验证电话号码,但我无法验证。我浏览了它,但没有得到任何满意的解决办法。 我从StackOverflow实现了一些代码,但出现异常“Unhanded Exception:type”(FirebaseUser)=>Null'不是type Cast“中类型”(AuthCredential)=>Void“的子类型,因此无法捕获该异常。 pubspec.ya

  • Firebase电话认证自动发送otp,不填写edittext。otp是在edittext中手动输入的。如何自动检测传入的验证短信并使用用户操作执行验证? Otp.kt

  • 我基本上创建了2个Xml。一个是用户输入电话号码,然后按下按钮,它会转到OTP验证屏幕。但这里的问题是我没有收到来自Firebase的任何OTP,但5秒后我收到一条敬酒消息,验证失败。如果我甚至没有收到消息,它怎么会失败。我还尝试输入另一个号码,以便我可以手动输入代码。但是Firebase没有向我发送OTP。 基本实现---点击忘记密码- 另外,我已经在Firebase中启用了电话身份验证。 Ot

  • 我正在android应用程序中使用Firebase SDK进行手机身份验证OTP验证。这在调试版本上运行良好,但在发布版本上不起作用。 在Firebase项目中添加了我的调试SHA-1指纹。 在Firebase项目中添加了我的发布认证SHA-1指纹。 我还没有发布/发布构建到google play store。 提前谢谢

  • 我的电话号码是字符串,如“91 96001 64500”(从google places API获取数据),我想提取电话号码(不带国家代码)以及国家代码,而不知道国家(国家可以是任何国家)。我怎样才能在弗利特做到这一点。 注意:已经有另一个完全相同的问题被问到,从电话号码[libphonenumber]中提取代码国家,但它是针对android的,我希望它是针对Flatter的。