Reputation: 1454
I'm trying to login a user & check if a user is new or not & if he/she is new give that particular user 1000 coins, however every time the user logs out & logs in even if they aren't new (they already exist in my database) the user's coins change to 1000, am I doing something wrong?
int coins = 1000;
Future<GoogleSignInAccount> _handleGoogleSignIn() async {
try {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
FirebaseUser firebaseUser =
(await _auth.signInWithCredential(credential)).user;
if (firebaseUser != null) {
final QuerySnapshot result = await Firestore.instance
.collection('u')
.where('id', isEqualTo: firebaseUser.uid)
.getDocuments();
final List<DocumentSnapshot> documents = result.documents;
if (documents.length == 0) {
// Update data to server if new user
Firestore.instance
.collection('u')
.document(firebaseUser.uid)
.setData({
'coins': coins,
});
}
}
return googleUser;
} catch (error) {
return error;
}
}
Upvotes: 1
Views: 87
Reputation: 599581
You have a mismatch between your query and the way you store your data.
You store you data as:
Firestore.instance
.collection('u')
.document(firebaseUser.uid)
.setData({
'coins': coins,
});
So each user is stored in a document that has their UID as the key, and that has a single field called coins
.
Then when you try to load this document, you do:
final QuerySnapshot result = await Firestore.instance
.collection('u')
.where('id', isEqualTo: firebaseUser.uid)
.getDocuments();
This query looks for documents that have a field id
with the value of the user's UID. And since your documents only contain a coins
field, there is no document that matches this query.
The solution is to use a direct lookup of the user's document, instead of a query:
final DocumentSnapshot result = await Firestore.instance
.collection('u')
.document(firebaseUser.uid)
.get();
if (!documents.exists) {
...
Upvotes: 2