Search code examples
fluttergoogle-cloud-firestoreflutter-dependencies

How to read user's data in cloud firestore in 2024


Am using below method to get user's data, how to display it on my screen? Pls guide as am not very fluent at flutter and firebase technologies yet and still learning. I have dug deeper into this still couldn't make sense how to display the data now.

DatabaseReference ref = FirebaseDatabase.instance.ref();

  Future readUserData() async {
    final ref = FirebaseDatabase.instance.ref();
    final snapshot = await ref.child('users/username').get();
    if (snapshot.exists) {
      print(snapshot.value);
    } else {
      print('No data available.');
    }
  }

Solution

  • The code in your question uses the API for the Realtime Database, while you claim to have data in Firestore. While both databases are part of Firebase, they are completely separate and the API for one cannot be used to access data in the other.

    For a complete, working example of how to show data from Firestore in your Flutter app, check the documentation here: https://firebase.google.com/docs/cpp/setup?platform=android#libraries-desktop. From there:

    class UserInformation extends StatefulWidget {
      @override
      _UserInformationState createState() => _UserInformationState();
    }
    
    class _UserInformationState extends State<UserInformation> {
      final Stream<QuerySnapshot> _usersStream =
          FirebaseFirestore.instance.collection('users').snapshots();
    
      @override
      Widget build(BuildContext context) {
        return StreamBuilder<QuerySnapshot>(
          stream: _usersStream,
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
    
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
    
            return ListView(
              children: snapshot.data!.docs
                  .map((DocumentSnapshot document) {
                    Map<String, dynamic> data =
                        document.data()! as Map<String, dynamic>;
                    return ListTile(
                      title: Text(data['full_name']),
                      subtitle: Text(data['company']),
                    );
                  })
                  .toList()
                  .cast(),
            );
          },
        );
      }
    }