如何在 flutter 中使用 firebase 设置 phone 身份验证?

How can I set phone authentication with firebase in flutter?

我正尝试在 flutter 中进行 phone 身份验证。我正在关注此 link:https://firebase.flutter.dev/docs/auth/phone 也尝试了一些教程,但仍然无效。短信来了,但是当我输入时,

the verification id used to create the phone auth credential is invalid

此错误出现在日志中。使用该代码:28183。我会出错吗? 非常感谢你提前。 这是我的 phone 授权页面:

import 'package:abcde/authentication_screen/after_auth.dart';
import 'package:abcde/authentication_screen/sms_code.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

/*enum MobileVerificationState {
  SHOW_MOBILE_FORM_STATE,
  SHOW_OTP_FORM_STATE,
}*/

class PhoneLogin extends StatefulWidget {
  const PhoneLogin({Key? key}) : super(key: key);
  static const String pathId = 'PhoneLogin';

  @override
  State<PhoneLogin> createState() => _PhoneLoginState();
}

class _PhoneLoginState extends State<PhoneLogin> {
/*  MobileVerificationState currentState =
      MobileVerificationState.SHOW_MOBILE_FORM_STATE;*/
  String _phoneNumber = '';
  String _smsCode = '';

  final _auth = FirebaseAuth.instance;

 // bool _isLoading = false;
  String verificationId = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Verify Phone Number'),
      ),
      body: SizedBox.expand(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                keyboardType: TextInputType.phone,
                decoration: const InputDecoration(hintText: 'Verify your phone'),
                onChanged: ((text) {
                  _phoneNumber = text;
                }),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            MaterialButton(
              onPressed: () async {
                if (_phoneNumber == '') {
                  const snackBar = SnackBar(
                      content: Text('Please, enter your phone number'));
                  ScaffoldMessenger.of(context).showSnackBar(snackBar);
                } else {
                  print(_phoneNumber);
/*                  setState(() {
                    _isLoading = true;
                    print(_phoneNumber);
                  });*/
                }
                try {
                  await _auth.verifyPhoneNumber(
                    timeout: const Duration(seconds: 60),

                    phoneNumber: _phoneNumber,

                    codeAutoRetrievalTimeout: (String verificationId) {},

                    verificationCompleted:
                        (PhoneAuthCredential phoneAuthCredential) async {
                      await _auth.signInWithCredential(phoneAuthCredential);
                    },
                    codeSent: (String verificationId,
                        int? forceResendingToken) async {
                      String smsCode = _smsCode;
                      PhoneAuthCredential credential =
                          PhoneAuthProvider.credential(
                              verificationId: verificationId, smsCode: smsCode);
                      await _auth.signInWithCredential(credential);
                    },

                    verificationFailed: (FirebaseAuthException error) {
                      if (error.code == 'invalid-phone-number') {
                        print('The provided phone number is not valid.');
                      }
                    },
                  );
                } catch (e) {
                  print(e);
                }
              },
              child: const Text('Verify'),
              color: Colors.blue,
            ),
            const SizedBox(
              height: 20,
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                keyboardType: TextInputType.number,
                decoration:
                    const InputDecoration(hintText: 'Enter your  sms code',),
                onChanged: ((text) {
                  _smsCode = text;
                }),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            MaterialButton(
              onPressed: () async {
                if (_smsCode == '') {
                  const snackBar =
                      SnackBar(content: Text('Please, enter SMS Code'));
                  ScaffoldMessenger.of(context).showSnackBar(snackBar);
                } else {
                  print(_smsCode);
/*                  setState(() {
                    _isLoading = true;
                    print(_smsCode);
                  });*/
                }
                try {
                  PhoneAuthCredential phoneAuthCredential =
                      PhoneAuthProvider.credential(
                          verificationId: verificationId, smsCode: _smsCode);
                  await _auth.signInWithCredential(phoneAuthCredential);
                  // signInWithPhoneAuthCredential(phoneAuthCredential);
                  Navigator.pushNamed(context, AfterAuth.pathId);
                } catch (e) {
                  print(e);
                }
              },
              child: const Text('Login'),
              color: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }
}

您还没有为局部变量赋值String verificationId = ''; 您此时在登录按钮的 onpressed 函数中使用该 verificationId 它将始终为空字符串

尝试在

分配 verificationId id
 codeSent: (String verificationIdFromFirebase,
                    int? forceResendingToken) async {
     verificationId = verificationIdFromFirebase;
                  String smsCode = _smsCode;
                  PhoneAuthCredential credential =
                      PhoneAuthProvider.credential(
                          verificationId: verificationId, smsCode: smsCode);
                  await _auth.signInWithCredential(credential);
}