Flutter:未处理异常:[firebase_auth/invalid-verification-id]用于创建电话身份验证凭据的验证ID无效

olhwl3o2  于 2023-04-07  发布在  Flutter
关注(0)|答案(1)|浏览(145)

我是新的Flutter.我试图使一个小的原型在Flutter,用户可以登录使用的电话号码和otp发送使用firebase.但我被困在这里,不知道如何解决错误.请帮助我弄清楚.谢谢.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:otp_login/OTP_Successful.dart';

class SendOtp extends StatefulWidget {
  static var verify="";
  const SendOtp({Key? key}) : super(key: key);

  @override
  State<SendOtp> createState() => _SendOtpState();
}

class _SendOtpState extends State<SendOtp> {
  TextEditingController phoneController = TextEditingController();
  TextEditingController otpController = TextEditingController();
  final FirebaseAuth auth = FirebaseAuth.instance;
  String? verificationId;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Send OTP"),
      ),
      body: Center(
        child: ListView(
          children: [
            TextFormField(
              controller: phoneController,
              decoration:
                  const InputDecoration(labelText: "Enter Phone Number"),
            ),
            const SizedBox(
              height: 5,
            ),
            ElevatedButton(
                onPressed: () async {
                  await FirebaseAuth.instance.verifyPhoneNumber(
                    phoneNumber: "${phoneController.text}",
                    verificationCompleted: (PhoneAuthCredential credential) {},
                    verificationFailed: (FirebaseAuthException e) {},
                    codeSent: (String verificationId, int? resendToken) {
                      setState(() {
                        this.verificationId = verificationId;
                      });
                      //SendOtp.verify = verificationId;
                      showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('Enter OTP'),
                              content: TextFormField(
                                decoration: const InputDecoration(labelText: "OTP"),
                              ),
                              actions: [
                                ElevatedButton(
                                    onPressed: () async {
                                      print("Verification : $verificationId");
                                      PhoneAuthCredential credential = PhoneAuthProvider.credential(verificationId: verificationId!, smsCode: otpController.text);

                                      // Sign the user in (or link) with the credential
                                      await auth.signInWithCredential(credential);
                                      Navigator.push(context, MaterialPageRoute(builder: (context)=>OtpSuccessful()));

                                    }, child: const Text("OK"))
                              ],
                            );
                          });
                    },
                    codeAutoRetrievalTimeout: (String verificationId) {},
                  );

                },
                child: const Text("Send OTP"))
          ],
        ),
      ),
    );
  }
}

在该页面中,用户将输入其电话号码,包括国家代码(没有任何空格),并按下“发送OTP”按钮,OTP将在其电话上发送,同时将打开一个警报框,用户必须输入OTP并按下“确定”按钮,按下该按钮,用户将按下名为“OtpSuccessful”的发送屏幕。
我在输入OTP后按下警报框的按钮时出现错误。请帮助。谢谢。

pkwftd7m

pkwftd7m1#

要解决此问题,您应该在使用verificationId变量创建凭据之前检查该变量的值。您还可以添加错误处理,以应对verificationId无效的情况。
下面是经过修改的更新代码片段:

ElevatedButton(
  onPressed: () async {
    await FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: "${phoneController.text}",
      verificationCompleted: (PhoneAuthCredential credential) {},
      verificationFailed: (FirebaseAuthException e) {},
      codeSent: (String verificationId, int? resendToken) {
        setState(() {
          this.verificationId = verificationId;
        });
        //SendOtp.verify = verificationId;
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('Enter OTP'),
              content: TextFormField(
                controller: otpController, // add this line
                decoration: const InputDecoration(labelText: "OTP"),
              ),
              actions: [
                ElevatedButton(
                  onPressed: () async {
                    if (verificationId == null || otpController.text.isEmpty) {
                      // add error handling for invalid verificationId or empty OTP
                      return;
                    }
                    print("Verification : $verificationId");
                    PhoneAuthCredential credential = PhoneAuthProvider.credential(
                      verificationId: verificationId!,
                      smsCode: otpController.text,
                    );

                    // Sign the user in (or link) with the credential
                    await auth.signInWithCredential(credential);
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => OtpSuccessful()),
                    );
                  },
                  child: const Text("OK"),
                ),
              ],
            );
          },
        );
      },
      codeAutoRetrievalTimeout: (String verificationId) {},
    );
  },
  child: const Text("Send OTP"),
),

相关问题