Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Get the current user's document in firebase firestore

I am using firebase email and password auth to login/register users, when a user is created a new document with extra information (profile info that include: username, email, avatar, phone...) is created with the id of that document being the firebaseAuth.currentUser.uid. when a user login using his account a main page that contains an AppBar() should display the user's full name, for that I created a method in my auth_services.dart that retrieves the current user's document and returns an object EndUser I got most of it done but

the problem is when I try to read the retrieved data it returns null

this is the method that fetches a user's document based on his uid:

Future<DocumentSnapshot> fetchCurrentUser(String uuid) async {
    return await firebaseFirestore.collection('users').doc(uuid).get();
}

and this is the main_page.dart where I am supposed to read the data:

class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Header(), //where I am supposed to display data
      ),
      //body: ...   
    );
  }
}

//this is the header widget


class Header extends StatefulWidget {
  @override
  _HeaderState createState() => _HeaderState();
}

class _HeaderState extends State<Header> {
   @override
   Widget build(BuildContext context) {
     return Container(
       child: FutureBuilder<DocumentSnapshot>(
       future: _autheService.fetchCurrentUser(firebaseAuth.currentUser.uid),
       builder: (context, snapshot) {
         if (snapshot.hasData) {
           return Row(
             children: [
               Text(snapshot.data.data()['fullname'],),
             ],
           );
         } else {
           print("err is: " + snapshot.data.data()); //null 
           return Text('empty');
         }
       },
    ));
  }
}

firebase-firestore user: enter image description here

like image 579
Thorvald Avatar asked May 17 '26 02:05

Thorvald


1 Answers

I tried the following and was able to get it working:

FutureBuilder<DocumentSnapshot>(
   future: _autheService.fetchCurrentUser(firebaseAuth.currentUser.uid),
   //added AsyncSnapshot<DocumentSnapshot>
   builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      //...   
   }
)
like image 104
Thorvald Avatar answered May 18 '26 21:05

Thorvald