1

I have an issue with utilising the current user's id (UID). The following code 'works' however there are instances where the _currentUID first outputs a 'null' before outputting the correct value.

class _ContactsScreenState extends State<ContactsScreen> {

 String _currentUID;

 @override
 initState() {
   super.initState();
   loadCurrentUser();
 }

 loadCurrentUser() async {
   var currentUID = await _getCurrentUID();
   setState(() {
     this._currentUID = currentUID;
   });
 }

 Future<String> _getCurrentUID() async {
   FirebaseUser user = await FirebaseAuth.instance.currentUser();
   return user.uid;
 }

 @override
 Widget build(BuildContext context) {

   if (_currentUID == null){
     print("current UserID = null");
   } else {
     print("current UserID = $_currentUID");
   }

   return StreamBuilder(
      ...

So this is actually working fine, outputs the results as expected, however upon inspection the printed output is as follows:

flutter: current UserID = null // why is it printing null?
flutter: current UserID = abcd1234abcd //correct

What is unusual is that this will only occur when the user visit's the screen for the 2nd time. The first time the screen/page loads it will correctly output 'only' the actual Current User ID. It when the user goes back to the same page it then will print current user twice (as shown above).

2
  • 1
    I think this can happen when the auth object has not finished initializing. To avoid that you can use the AuthStateListener. Commented Mar 14, 2019 at 13:19
  • Make sure that you don't navigate to screen before auth operation is completed. Also the currentUser() function is not async. Commented Mar 14, 2019 at 13:22

1 Answer 1

1

This is perfectly normal.

loadCurrentUser is async, so will complete some time after the instance if _ContactsScreenState is created. Only then will _currentUID be assigned.

If the framework calls build before that assignment, then it will be null. It's normal to have build simply return Container or a progress indicator if it's null. Once it it assigned, build will be called again. This time it will not be null and you can build the 'normal' screen.

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

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.