I'm trying to check if a user is already registered or if i need to create a new account.
The idea was that i wanted to get a list of users and check if my new email matches up. If not create a new user
I have a DatabaseService
class which I use to get my data, and a AuthService
which i use to perform login and registration.
I my DatabaseService
class I have a function to return a list of User
objects:
List<User> getUserList() {
print(databaseReference);
List<User> userList = [];
databaseReference
.collection("users")
.getDocuments()
.then((QuerySnapshot snapshot) {
print('s');
snapshot.documents.forEach((doc) {
print(doc.documentID);
userList.add(User(
uid: doc.documentID,
email: doc.data['email'],
name: doc.data['name'],
imgUrl: doc.data['imgUrl'],
));
print(userList);
});
});
return userList;
}
This works fine when I call it from my LoginPage
. I get a list with all my auhtorized users. But when i run it out of my loginIfRegistered
function in my AuthService
class. I just get an empty list. this is the function:
Future loginIfRegistered(String email, String password, List<User> userList) async {
print('CHECKING IF ALREADY REGISTERED');
bool alreadyRegistered = false;
updateUserList();
for (var user in userList) {
if (user.email == email) {
alreadyRegistered = true;
}
}
if (userList.length == 0) {
alreadyRegistered = false;
}
if (alreadyRegistered) {
// sign in
print('ALREADY REGISTERED');
try {
return await _auth.signInWithEmailAndPassword(
email: email, password: password);
} catch (e) {
print(e.toString());
return e;
}
} else {
print('NOT REGISTERED');
// register
return null;
}
}
But when I pass the userList
as a parameter into my function (Future loginIfRegistered(String email, String password, List<User> userList) async {...}
), and initialize it on my LoginPage
there is no problem.
I also tried getting the list at the top of my AuthService
and it worked aswell, but I don't want it to be just updated when AuthService
is initialized but rather when i hit the SignIn button.
I also tried adding a updateUserList
function in AuthService
which is called in loginIfRegistered()
but that also doesn't work.
So why do I get an empty list if i call getUserList()
?
To recap: I want to have a login page which also registers you if you don't already have an account.
When I press the LogIn Button the function SigninIfRegisters
(in AuthService
) is run which needs to know all users in my firestore Database (I made a collection for all my users, not out of Firebaseauth
or something like that (is that a good idea?)). Therefore i made a function in DatabaseService
which gives me a List<User>
this works fine if called out of the LoginPage
but not out of any functions in AuthService
. If i instantiate List<User>
not in any function in AuthService
it also works.
请有人解释为什么???