Firebase 使用电话号码保持登录状态
如何使用电话号码注册并在注销前保持登录状态。我正在使用Flatter,我已经可以用电话号码注册用户,但当应用程序重新打开时,它会从登录页面开始 我们的想法是在注册后,甚至在应用程序关闭后保持登录状态。而且我也不能做循环指示器来显示应用程序正在加载(如果你也教我怎么做,我会很高兴的) 这是我的密码Firebase 使用电话号码保持登录状态,firebase,flutter,authentication,Firebase,Flutter,Authentication,如何使用电话号码注册并在注销前保持登录状态。我正在使用Flatter,我已经可以用电话号码注册用户,但当应用程序重新打开时,它会从登录页面开始 我们的想法是在注册后,甚至在应用程序关闭后保持登录状态。而且我也不能做循环指示器来显示应用程序正在加载(如果你也教我怎么做,我会很高兴的) 这是我的密码 import 'package:country_code_picker/country_code_picker.dart'; import 'package:firebase_auth/firebase
import 'package:country_code_picker/country_code_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'BottomBarPages/home.dart';
class SignIn extends StatefulWidget {
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
TextEditingController phoneController = new TextEditingController();
String phoneNumber = "";
bool shower = false;
String smsCode;
String verificationCode;
void _onCountryChange(CountryCode countryCode) {
this.phoneNumber = countryCode.toString();
print("New Country selected: " + countryCode.toString());
}
void check() {
final myPhone = this.phoneNumber + phoneController.text;
print("Full Text: " + myPhone);
}
Future<void> man() async{
}
Future<void> submit() async {
final myPhone = this.phoneNumber + phoneController.text;
final PhoneVerificationCompleted verificationCompleted =
(AuthCredential credential) {
setState(() {
print(credential);
});
};
final PhoneVerificationFailed verificationFailed =
(AuthException exception) {};
final PhoneCodeSent phoneCodeSent = (String verId, [int forceCodeResend]) {
this.verificationCode = verId;
smsCodeDialog(context).then((value) => print("signed"));
};
final PhoneCodeAutoRetrievalTimeout autoRetrievalTimeout = (String verId) {
this.verificationCode = verId;
};
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: myPhone,
timeout: const Duration(seconds: 5),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: phoneCodeSent,
codeAutoRetrievalTimeout: autoRetrievalTimeout);
}
Future<bool> smsCodeDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
'Enter Code',
style: TextStyle(color: Colors.lightGreen, fontSize: 24),
),
content: TextField(
keyboardType: TextInputType.number,
onChanged: (Value) {
smsCode = Value;
},
),
contentPadding: EdgeInsets.all(10),
actions: [
FlatButton(
onPressed: () {
FirebaseAuth.instance.currentUser().then((user) {
if (user != null) {
Navigator.of(context).pop();
Navigator.push(context,
MaterialPageRoute(builder: (context) => Home()));
} else {
Navigator.of(context).pop();
signIn();
}
});
},
child: Text(
'Verify',
style: TextStyle(fontSize: 20, color: Colors.lightGreen),
))
],
);
});
// CircularProgressIndicator(
// valueColor: new AlwaysStoppedAnimation<Color>(Colors.lightGreen),
// value: 0.25,
// );
}
signIn() {
AuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(
verificationId: verificationCode, smsCode: smsCode);
FirebaseAuth.instance
.signInWithCredential(phoneAuthCredential)
.then((user) => Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())))
.catchError((e) => print(e));
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
body: Column(
//mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 1,
child: Container(
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
stops: [0.1, 0.3, 1.0],
colors: [
Colors.lightGreen[300],
Colors.white,
Colors.lightGreen[50]
],
),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 150,
child: Image.asset('images/phone.png'),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
border: Border.all(color: Colors.lightGreen)),
width: double.infinity,
height: 40,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Row(
// crossAxisAlignment: CrossAxisAlignment.start,
//mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CountryCodePicker(
dialogTextStyle: TextStyle(fontSize: 20),
onChanged: _onCountryChange,
initialSelection: 'US',
favorite: ['+251', 'ET'],
),
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: SizedBox(
width: 150,
child: TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
border: InputBorder.none,
),
),
),
),
],
),
),
),
),
SizedBox(
height: 20,
),
MaterialButton(
onPressed: submit,
minWidth: MediaQuery.of(context).size.width - 80,
height: 45,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Colors.lightGreen,
splashColor: Colors.green,
child: Text(
"Confirm",
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
Padding(
padding:
EdgeInsets.symmetric(vertical: 14, horizontal: 64),
child: Text(
"you'll receive a 6 digit code click Confirm to verify",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22,
color: Colors.lightGreen,
),
),
),
],
),
),
),
),
],
),
),
);
}
}
import'程序包:country\u code\u picker/country\u code\u picker.dart';
导入“包:firebase_auth/firebase_auth.dart”;
进口“包装:颤振/材料.省道”;
导入'BottomBarPages/home.dart';
类签名扩展StatefulWidget{
@凌驾
_SignInState createState()=>\u SignInState();
}
类_SignInState扩展状态{
TextEditingController电话控制器=新的TextEditingController();
字符串phoneNumber=“”;
布尔阵雨=假;
字符串smsCode;
字符串验证码;
void\u onCountryChange(国家代码国家代码){
this.phoneNumber=countryCode.toString();
打印(“选择的新国家:+countryCode.toString());
}
无效检查(){
final myPhone=this.phoneNumber+phoneController.text;
打印(“全文:+myPhone”);
}
未来人()异步{
}
Future submit()异步{
final myPhone=this.phoneNumber+phoneController.text;
最终电话验证已完成验证已完成=
(认证凭证){
设置状态(){
打印(凭证);
});
};
最终电话验证失败验证失败=
(授权例外){};
final PhoneCodeSent PhoneCodeSent=(字符串verId,[int-forceCodeResend]){
this.verificationCode=verId;
smsCodeDialog(上下文)。然后((值)=>打印(“签名”);
};
最终PhoneCodeAutoRetrievalTimeout autoRetrievalTimeout=(字符串verId){
this.verificationCode=verId;
};
等待FirebaseAuth.instance.verifyPhoneNumber(
电话号码:myPhone,
超时:常量持续时间(秒数:5),
验证完成:验证完成,
验证失败:验证失败,
codeSent:phoneCodeSent,
codeAutoRetrievalTimeout:autoRetrievalTimeout);
}
未来smsCodeDialog(构建上下文){
返回显示对话框(
上下文:上下文,
禁止:错误,
生成器:(BuildContext上下文){
返回警报对话框(
标题:正文(
“输入代码”,
样式:TextStyle(颜色:Colors.lightGreen,字体大小:24),
),
内容:TextField(
键盘类型:TextInputType.number,
一旦更改:(值){
smsCode=值;
},
),
contentPadding:EdgeInsets.all(10),
行动:[
扁平按钮(
已按下:(){
FirebaseAuth.instance.currentUser().then((用户){
如果(用户!=null){
Navigator.of(context.pop();
Navigator.push(上下文,
MaterialPackageRoute(生成器:(上下文)=>Home());
}否则{
Navigator.of(context.pop();
签名();
}
});
},
子:文本(
“核实”,
样式:TextStyle(字体大小:20,颜色:Colors.浅绿色),
))
],
);
});
//循环压缩机指示器(
//valueColor:new AlwaysStoppedAnimation(颜色:浅绿色),
//数值:0.25,
// );
}
签名(){
AuthCredential phoneAuthCredential=PhoneAuthProvider.getCredential(
验证ID:verificationCode,smsCode:smsCode);
FirebaseAuth.instance
.signInWithCredential(phoneAuthCredential)
.然后((用户)=>Navigator.push(
上下文,MaterialPage路由(生成器:(上下文)=>Home())
.catchError((e)=>打印(e));
}
@凌驾
小部件构建(构建上下文){
返回手势检测器(
onTap:(){
FocusScopeNode currentFocus=FocusScope.of(上下文);
如果(!currentFocus.hasPrimaryFocus){
currentFocus.unfocus();
}
},
孩子:脚手架(
正文:专栏(
//mainAxisAlignment:mainAxisAlignment.start,
儿童:[
扩大(
弹性:1,
子:容器(
高度:MediaQuery.of(context).size.height,
装饰:盒子装饰(
梯度:线性梯度(
开始:Alignment.topLeft,
结束:对齐。右下角,
停止:[0.1,0.3,1.0],
颜色:[
颜色。浅绿色[300],
颜色,白色,
颜色。浅绿色[50]
],
),
),
孩子:填充(
填充:常量边集。对称(垂直:15),
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
大小盒子(
身高:150,
子项:Image.asset('images/phone.png'),
),
大小盒子(
身高:20,
),
填充物(
填充:常量边集。对称(水平:20),
子:容器(
装饰:盒子装饰(
边界半径:边界半径。圆形(50),
边框:边框。全部(颜色:Colors.lightGreen)),
宽度:double.infinity,
高度:
User user = FirebaseAuth.instance.currentUser;
@override
void initState() {
super.initState();
getUser();
}
getUser() {
User firebaseUser = FirebaseAuth.instance.currentUser;
if (firebaseUser != null)
WidgetsBinding.instance.addPostFrameCallback((_) =>
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => HomePage())));
}