Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read data from the Flutter Firebase Real-Time Database?

Tags:

flutter

dart

I've used the Real-Time Database with this setup:

->users
->uid
    ->name
    ->email
    ->other info

If I wanted to save the user data I would use my User class and then set the object in the database like this:

final FirebaseUser user = await FirebaseAuth.instance.currentUser(); FirebaseDatabase.instance.reference().child("kullanıcılar").child(user.uid).child("takip").set({"uid":"uid"});

I tried it and it works fine.

But how can I retrieve these values from the database? For instance, once I set a User object as shown above, I may want to retrieve the user's email. I don't mean getting the email through the sign-in provider. I want the email through the real-time database. I've tried working this out for a while now but the documentation isn't helping much. All it shows is to setup listeners in order to wait for changes to the data. But I'm not waiting for changes, I don't want a listener. I want to directly get the values in the database by using the keys in the JSON tree. Is this possible via the real-time database? If so, how can it be done because either the documentation doesn't explain it or I'm just not understanding it.Thanks.

like image 839
Ceyhun Er Avatar asked Mar 04 '23 17:03

Ceyhun Er


2 Answers

You can retrieve the value once using .once(). Here's an example: https://github.com/flutter/plugins/blob/master/packages/firebase_database/example/lib/main.dart#L62

or better, with async/await:

Future<String> getEmail() async {
  String result = (await FirebaseDatabase.instance.reference().child("path/to/user/record/email").once()).value;
  print(result);
  return result;
}
like image 112
Gazihan Alankus Avatar answered Mar 06 '23 10:03

Gazihan Alankus


You can't retrieve the single value from firebase, it always return the DocumentSnapshot of the whole record. You can get a single record from user table by using user id like this:

getData() async {
  final FirebaseUser user = await _firebaseAuth.currentUser();
  return await FirebaseDatabase.instance.reference().child('user').equalTo(user.uid);
}

Get it like this:

getData().then((val){
    print(val.email);
});
like image 30
Muhammad Noman Avatar answered Mar 06 '23 10:03

Muhammad Noman