Home > database >  How to get name and phone number from realtime database in flutter?
How to get name and phone number from realtime database in flutter?

Time:07-08

I have one user in my database:

Users { 
    userId: Xx1j9Pih4BPnu01vnFdMfZqGOr02: {name: 'jack5' ,phone: '0845204281'
  }
}

So far I have the following function for getting data from the realtime firebase database.

static Future<dynamic> getCurrentUserInfo() async {
  String? userId = FirebaseAuth.instance.currentUser?.uid;
  final ref = FirebaseDatabase.instance.ref();
  final snapshot = await ref.child('users/$userId').get();
  if (snapshot.exists) {
    return snapshot.value;
  } else {
    print('No data available.');
    return '';
  }

The function returns an object. How do I convert this object into a string? Or: How do I simply get the name of the current user of my database?

CodePudding user response:

static Future<dynamic> getCurrentUserInfo() async {
  String? userId = FirebaseAuth.instance.currentUser?.uid;
  final ref = FirebaseDatabase.instance.ref();
  final snapshot = await ref.child('users/$userId').get();
  if (snapshot.exists) {
    Map<dynamic, dynamic> values = needsSnapshot.value;
    values.forEach((key, values) {
      print(values['name']);
      print(values['phone']);
    });
  } else {
    print('No data available.');
    return '';
  }
}

CodePudding user response:

If you just want to get the name property of the user, assuming your users are stored by their UID, that'd be:

final snapshot = await ref.child('users/$userId/name').get();
print(snapshot.value);
  • Related