使用Flutter中的当前用户uid获取Firebase数据

9rygscc1  于 2022-12-27  发布在  Flutter
关注(0)|答案(1)|浏览(177)

我想在flutter中使用Firebase创建一个聊天应用程序,我必须在屏幕上显示当前用户的“名称”。我尝试了一种方法,但似乎不起作用。它给我留下了一个空白文本。

String myName = '';
  String myUsername = '';

  Future<void> _getCurrentUserName() async {
    final uid = FirebaseAuth.instance.currentUser!.uid;

    FirebaseFirestore.instance
        .collection("users")
        .doc(uid)
        .get()
        .then((snapshot) {
      setState(() {
        myName = snapshot['name'].toString();
        myUsername = snapshot['username'].toString();
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _getCurrentUserName();
  }

你能帮帮我吗?先谢了。

sqyvllje

sqyvllje1#

试试这个:

String myName = '';
  String myUsername = '';

  Future<void> _getCurrentUserName() async {
    final uid = FirebaseAuth.instance.currentUser!.uid;

    FirebaseFirestore.instance
        .collection("users")
        .doc(uid)
        .get()
        .then((snapshot) {
      setState(() {
        myName = (snapshot.data() as Map<String, dynamic>)['name'].toString(); // change this
        myUsername = (snapshot.data() as Map<String, dynamic>)['username'].toString(); // and this
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _getCurrentUserName();
  }

相关问题