Reputation: 27
I have a problem with my redirection. I would like to redirect my user if it is new to my registerscreen, if not new to my topnavigationscreen.
To check if the user exists I would like to get some information from "cloud firestore" which is created in my registerscreen. But I can't get them back.
My little code:
void registergoogleUser() async {
await _userProvider
.registergoogleUser( _scaffoldKey)
.then((response) async {
if (response is Success<UserCredential>) {
Future<DocumentSnapshot> getUser(String userId) async {
final FirebaseFirestore instance = FirebaseFirestore.instance;
print (await instance.collection('users')?.doc(userId)?.get());// for test
(await instance.collection('users')?.doc(userId)?.get());
}
print (getUser);
if (await getUser != null) {
Navigator.of(context).pushNamedAndRemoveUntil(
TopNavigationScreen.id, (route) => false);
} else {
Navigator.pop(context);
Navigator.pushNamed(context, RegisterScreen.id);
}
}});
}
But my "run" return this:
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist
and my
print (instance.collection('users').doc(userId).get());
return this:
I/flutter (25671): Closure: (String) => Future
you can see my code (for variables and other) here:
Upvotes: 1
Views: 144
Reputation: 315
Apart from this, to check if a user exists you can use FirebaseAuth like this:
void _checkIfExsist(String email) async {
// final _auth = FirebaseAuth.instance;
final _list = await _auth.fetchSignInMethodsForEmail(email);
if(_list.isEmpty){
//User not registered
} else {
//User registered
}
}
EDIT
As said by other user before, you need to await Future:
void registergoogleUser() async {
await _userProvider
.registergoogleUser( _scaffoldKey)
.then((response) async {
if (response is Success<UserCredential>) {
// You need to await the Futures!
Future<DocumentSnapshot> getUser(String userId) async {
final FirebaseFirestore instance = FirebaseFirestore.instance;
print (instance.collection('users')?.doc(userId)?.get()); //print for test
return instance.collection('users')?.doc(userId)?.get();
}
final result = await getUser(userId);
if (result != null) {
Navigator.of(context).pushNamedAndRemoveUntil(
TopNavigationScreen.id, (route) => false);
} else {
Navigator.pop(context);
Navigator.pushNamed(context, RegisterScreen.id);
}
}
}
);
}
Upvotes: 0
Reputation: 3136
Here
print(await instance.collection('users').doc(userId).get())
you are using Future as synchronous call. You must await
for value then if docs not null use get
on it. By the way in cases like this use ?.
operator to be null-safe, like
print(await instance.collection('users')?.doc(userId)?.get())
Upvotes: 1