В моем приложении есть адрес электронной почты и телефон для регистрации. Если я вхожу в систему с правильной информацией, я отправляю ее прямо на домашнюю страницу, однако при входе с аутентификацией по телефону я возвращаюсь на страницу авторизации.и только позволяет мне войти на домашнюю страницу, если я перезагружаюсь, я даже пытался перейти непосредственно на домашнюю страницу после завершения аутентификации, но я, кажется, не распознаю, что я вошел в систему, пока я не перезагружусь, есть идеи, как я могу справиться с этим?
код аутентификации:
String phoneNo;
String smsCode;
String verificationId;
String uid;
Future<void> verifyPhone() async {
final PhoneCodeAutoRetrievalTimeout autoRetrieve = (String verId) {
this.verificationId = verId;
};
final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
this.verificationId = verId;
smsCodeDialog(context).then((value) {
print('Signed in');
});
};
final PhoneVerificationCompleted verifiedSuccess = (FirebaseUser user) {
print('verified');
};
final PhoneVerificationFailed veriFailed = (AuthException exception) {
print('${exception.message}');
};
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: this.phoneNo,
codeAutoRetrievalTimeout: autoRetrieve,
codeSent: smsCodeSent,
timeout: const Duration(seconds: 5),
verificationCompleted: verifiedSuccess,
verificationFailed: veriFailed);
}
Future<bool> smsCodeDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('Enter sms Code'),
content: TextField(
onChanged: (value) {
this.smsCode = value;
},
),
contentPadding: EdgeInsets.all(10.0),
actions: <Widget>[
new FlatButton(
child: Text('Done'),
onPressed: () {
FirebaseAuth.instance.currentUser().then((user) {
if (user != null) {
setState(() {
this.uid = user.uid;
_submitForm(widget.model.authenticate, 2);
Navigator.of(context).pushReplacementNamed('/');
});
} else {
Navigator.of(context).pop();
signIn();
}
});
},
)
],
);
});
}
signIn() async {
_submitForm(widget.model.authenticate, 2);
}}
void _submitForm(Function authenticate, int option) async {if(option == 2) {
Map<String, dynamic> successInformation;
successInformation = await authenticate(
null, phoneNo, null, tokenValue, uid, verificationId, smsCode);
if (successInformation['success']) {
Navigator.pushReplacementNamed(context, '/');
}} else{
Map<String, dynamic> successInformation;
successInformation = await authenticate(_formData['Email'], null,
_formData['Password'], tokenValue, null, null, null, _authMode);
if (successInformation['success']) {
print('success');
Navigator.pushReplacementNamed(context, '/');
} }
Future<Map<String, dynamic>> authenticate(
String email,
String phone,
String password,
String token,
String id,
String verificationId,
String smsCode,
[AuthMode mode = AuthMode.Login]) async {
_isLoading = true;
notifyListeners();
String uid;
final Map<String, dynamic> authData = {
'email': email,
'password': password,
'returnSecureToken': true,
};
if (email != null) {
try {
FirebaseUser user = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
uid = user.uid;
} catch (error) {
_isLoading = false;
notifyListeners();
}
} else {
FirebaseUser user = await FirebaseAuth.instance.signInWithPhoneNumber(
verificationId: verificationId, smsCode: smsCode);
print(user);
uid = user.uid;
}
_authenticatedUser =
User(id: uid, phone: phone, email: email, token: token);
setAuthTimeout(int.parse(1000.toString()));
_userSubject.add(true);
email == null
? addTokenPhone(token, _authenticatedUser.phone, uid)
: addToken(token, _authenticatedUser.email, uid);
final DateTime now = DateTime.now();
final DateTime expiryTime =
now.add(Duration(seconds: int.parse(10000.toString())));
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('token', uid);
prefs.setString('userEmail', email);
prefs.setString('phone', phone);
prefs.setString('userId', uid);
prefs.setString('expiryTime', expiryTime.toIso8601String());
_isLoading = false;
notifyListeners();
return {
'success': true,
'message': 'message',
};
}
void autoAuthenticate() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token');
final String expiryTimeString = prefs.getString('expiryTime');
if (token != null) {
final DateTime now = DateTime.now();
final parsedExpiryTime = DateTime.parse(expiryTimeString);
if (!verified) {
if (parsedExpiryTime.isBefore(now)) {
_authenticatedUser = null;
notifyListeners();
return;
}
}
final String userEmail = prefs.getString('userEmail');
final String phone = prefs.getString('phone');
final String userId = prefs.getString('userId');
final int tokenLifespan = parsedExpiryTime.difference(now).inSeconds;
_authenticatedUser =
User(id: userId, email: userEmail, phone: phone, token: token);
print(_authenticatedUser);
_userSubject.add(true);
setAuthTimeout(tokenLifespan);
notifyListeners();
}
}
И на моей домашней странице есть следующее состояние:
bool _isAuthenticated = false;
@override
void initState() {
_model.autoAuthenticate();
_model.userSubject.listen(
(bool isAuthenticated) {
setState(
() {
_isAuthenticated = isAuthenticated;
},
);
},
);
super.initState();
}
, и маршрут настроен так:
'/': (BuildContext context) =>
!_isAuthenticated ? AuthPage() : HomePage(),