Home > front end >  Fetch Firebase data with current user uid in Flutter
Fetch Firebase data with current user uid in Flutter

Time:12-26

I want to create a Chat app in flutter using Firebase and I have to show the current user "Name" on the screen. I tried a method but It doesnt seem to work. It leaves me with a blank Text.

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

Can you help me please ? Thanks in advance.

CodePudding user response:

try this :

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();
  }
  • Related