0
votes

Thanks in advance!

Flutter & Firestore

I'm checking if the user is an admin. I have a collection 'users', within: a bool: admin: true or false. If it's true it shows the admin Screen. Else it shows the main screen.

The problem: the first 1 second I get this Screen. (see screen shot, only 1 second visible) Is there an option to use a loading indicator when the app gets the data from firestore.

I tried adding if (currentUser.admin == null) {} But that doesn't work.

User currentUser; 
//I made a separate modal document 

@override
  void initState() {
    super.initState();
    pageController = PageController(initialPage: 0);
    getUser();
  } 

 getUser() async {
    final FirebaseUser user = await FirebaseAuth.instance.currentUser();
    DocumentSnapshot doc =
        await Firestore.instance.collection("users").document(user.uid).get();

    setState(() {
      currentUser = User.fromDocument(doc);
    });

    print(currentUser.admin);
  }



@override
  Widget build(BuildContext context) {
    if (currentUser.admin == true) {
      return AdminScreen(
        currentUser: currentUser,
      );
    } else {
      return mainScreen();
    }
  }
}

Screenshot

UPDATE: tried this: getUser() async { final FirebaseUser user = await FirebaseAuth.instance.currentUser(); DocumentSnapshot doc = await Firestore.instance.collection("users").document(user.uid).get();

if (doc.exists) {
  try {
    setState(() {
      currentUser = User.fromDocument(doc);
    });
  } catch (e) {
    print(e);
  }
}
2

2 Answers

0
votes

Found it!

For anyone having the same issue. This was the problem: if (currentUser.admin == true)

It should be: if (currentUser == null) or if (currentUser != null)

it doesn't work with currentUser.xxxx

0
votes

You can also do as follows

Firestore.instance
        .collection('driverListedRides')
        .getDocuments()
        .then((QuerySnapshot snapshot) => {
              snapshot.documents.forEach((f) {
                String _variableName = f.data["YourCollectionFieldId"];
              })
            });