Home > Software design >  How can I get current user document id/name from Firestore with Flutter?
How can I get current user document id/name from Firestore with Flutter?

Time:01-18

I'm new to flutter. I have problems with how to fetch the current user document ID/name using syntax.

  Future<User?> readUser() async {
    final docUser =
        FirebaseFirestore.instance.collection('users').doc('How do I get this document ID');
        
    final snapshot = await docUser.get();

    if (snapshot.exists) {
      return User.fromJson(snapshot.data()!);
    } else {
      print('User does not exist');
    }
  }

This is my User class where i store my details

class User {
  String uid;
  final String name;
  final int age;
  final String email;

  User({
    this.uid = '',
    required this.name,
    required this.age,
    required this.email,
  });
  Map<String, dynamic> toJson() => {
        'uid': uid,
        'name': name,
        'age': age,
        'email': email,
      };

  static User fromJson(Map<String, dynamic> json) => User(
        uid: json['id'],
        name: json['name'],
        age: json['age'],
        email: json['email'],
      );
}

I tried

final firebaseUser = await FirebaseAuth.instance.currentUser
  Future<User?> readUser() async {
    final docUser =
        FirebaseFirestore.instance.collection('users').doc(firebaseUser.uid);
        
    final snapshot = await docUser.get();

    if (snapshot.exists) {
      return User.fromJson(snapshot.data()!);
    } else {
      print('User does not exist');
    }
  }

But it does not work

the image for my firestore is here

CodePudding user response:

It's just snapshot.id

For example

  Future<T> get<T>({
    String path,
    T Function(Map<String, dynamic> data, String documentID) builder,
  }) async {
    final reference = FirebaseFirestore.instance.doc(path);
    final DocumentSnapshot snapshot = await reference.get();
    return builder(snapshot.data() as Map<String, dynamic>, snapshot.id);
  }

CodePudding user response:

To access the current user id use FirebaseAuth.instance.currentUser!.uid

To access the current user name use FirebaseAuth.instance.currentUser!.displayName


How to listen to the current user's document ?

class _UserInformationState extends State<UserInformation> {
  final _usersStream = FirebaseFirestore.instance
      .collection('users')
      .doc(FirebaseAuth.instance.currentUser!.uid) 
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: _usersStream,
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
            Map<String, dynamic> data =
                snapshot.data!.data()! as Map<String, dynamic>;
            return Text(data['fullName']);
          },
        ),
      ),
    );
  }
}
  • Related