简体   繁体   English

如何使用 Flutter 从 Firestore 获取当前用户文档 ID/名称?

[英]How can I get current user document id/name from Firestore with Flutter?

I'm new to flutter. I have problems with how to fetch the current user document ID/name using syntax.我是 flutter 的新手。我对如何使用语法获取当前用户文档 ID/名称有疑问。

  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,我在其中存储我的详细信息

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我的 Firestore 的图片在这里

To access the current user id use FirebaseAuth.instance.currentUser..uid要访问当前用户 ID,请使用FirebaseAuth.instance.currentUser..uid

To access the current user name use FirebaseAuth.instance.currentUser..displayName要访问当前用户名,请使用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']);
          },
        ),
      ),
    );
  }
}

It's just snapshot.id它只是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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM