我是新的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后按下警报框的按钮时出现错误。请帮助。谢谢。
1条答案
按热度按时间pkwftd7m1#
要解决此问题,您应该在使用verificationId变量创建凭据之前检查该变量的值。您还可以添加错误处理,以应对verificationId无效的情况。
下面是经过修改的更新代码片段: