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

km0tfn4u  于 2023-01-18  发布在  Flutter
关注(0)|答案(2)|浏览(157)

我是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');
    }
  }

这是我的User类,我在其中存储我的详细信息

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'],
      );
}

我试过了

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');
    }
  }

但它不起作用
the image for my firestore is here

s6fujrry

s6fujrry1#

只是一个月
例如

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);
  }
kmb7vmvb

kmb7vmvb2#

要访问当前用户ID,请使用**FirebaseAuth.instance.currentUser!.uid**
要访问当前用户名,请使用**FirebaseAuth.instance.currentUser!.displayName**

如何监听当前用户的文档?
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']);
          },
        ),
      ),
    );
  }
}

相关问题