0

why is the variable showing undefined? i clearly declared it above. any help is highly appreciated...i even tried declaring the variable as string, still didn't work

  createUser() async {
//Todo: check if user exists in database

GoogleSignInAccount user = googleSignIn.currentUser;
final doc = await usersRef.doc(user.id).get();

//Todo: if user don't exist then take them to set profile page

if (!doc.exists) {
  final username = await Navigator.push(
      context, MaterialPageRoute(builder: (context) => CreateAccount()));
}
//Todo: get user name from create account and create a new user

usersRef.doc(user.id).set({
  "id": user.id,
  "userName": username,
  "photourl": user.photoUrl,
  "displayName": user.displayName,
  "timeStamp": timestamp,
});

}

error shows undefined variable

2 Answers 2

2

The variable is not accessible as you are trying to access it out of its scope. You just have to use it within the {} (brackets) in which you have defined it.

createUser() async {
    //Todo: check if user exists in database

    GoogleSignInAccount user = googleSignIn.currentUser;
    final doc = await usersRef.doc(user.id).get();

    //Todo: if user don't exist then take them to set profile page

    if (!doc.exists) {
      final username = await Navigator.push(
          context, MaterialPageRoute(builder: (context) => CreateAccount()));
        usersRef.doc(user.id).set({
          "id": user.id,
          "userName": username,
          "photourl": user.photoUrl,
          "displayName": user.displayName,
          "timeStamp": timestamp,
        });
    }
    //Todo: get user name from create account and create a new user


}

Hope it will work for you now :).

Sign up to request clarification or add additional context in comments.

1 Comment

I just figured it out, thank you so much..such an idiot move on my part...
1

It's not working because you are defining the variable inside the if statement and where you are using is outside the if statement. So in a situation when the if statement condition is false, there is no variable called username and that's why you get the error

You have to put the code inside the if statement in order to use the variable:

if (!doc.exists) {
  final username = await Navigator.push(
      context, MaterialPageRoute(builder: (context) => CreateAccount()));
   usersRef.doc(user.id).set({
   "id": user.id,
   "userName": username,
   "photourl": user.photoUrl,
   "displayName": user.displayName,
   "timeStamp": timestamp,
    });
}
//Todo: get user name from create account and create a new user

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.