How to read data from Firebase Realtime database using Flutter/Dart - firebase

I am using Flutter and I would like to retrieve some data from my realtime database Firebase. I have the following data stored in the my realtime database Firebase:
How can I get each piece of information from it? For example I would like to get the name 'Tom' only?

Reading through firebase documentation you can see that how we read and write data from RTDMS firebase.
static Future<List<PostModel>> getPost() async {
Query postsSnapshot = await FirebaseDatabase.instance
.reference()
.child("posts")
.orderByKey();
print(postsSnapshot); // to debug and see if data is returned
List<PostModel> posts;
Map<dynamic, dynamic> values = postsSnapshot.data.value;
values.forEach((key, values) {
posts.add(values);
});
return posts;
}
your can call this function at the time of build the widget or after any action

FirebaseDatabase.instance.ref("users").onValue.listen((event) {
final data =
Map<String, dynamic>.from(event.snapshot.value as Map,);
data.forEach((key, value) {
log("$value");
});
});

Related

Flutter-Firestore: - Code to retrieve data from firestore then save/use it

I am very new to Dart, and coding in general. I have produced this code after watching tutorials on YouTube. For the most part, I have been able to troubleshoot most of my problems on my own, here I feel I need some help. I wanted to extract all the fields from a document and use it. I have tried a few codes but there is no proper solution anywhere online.
Here is the code I used to retrieve it:-
documentID = '9zjwixClgwR1Act1OlPK'
firebaseGetData(documentID){
firebaseFirestore.collection('course').doc(documentID).get().then((value) {
print(value.data());
});
}
Here is my database file structure:-
I want to store all the fields in variables and use them. please help me with the correct code, please.
There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries:
Call a method to get the data
const docRef=doc(db,’course’,'9zjwixClgwR1Act1OlPK')
getDoc(docRef)
.then((doc) => {
console.log(doc.data(),doc.id)
})
Set a listener to receive data-change events.
To get real-time data when you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.
const docRef=doc(db,’course’,'9zjwixClgwR1Act1OlPK')
onSnapshot(docRef,(doc) => {
console.log(doc.data(),doc.id)
})
For more information, kindly check link1 & link2
Firstly you need to create firestore instance. Your function must be async and return a Future value. Also, you can check this document.
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<Map<String, dynamic>> firebaseGetData({required String documentID}) async {
DocumentSnapshot ds =
await _firestore.collection("course").doc(documentID).get();
Map<String, dynamic> data = ds.data() as Map<String, dynamic>;
print(data["videoDescription"] as String); // check if it null or not
return data;
}
// creating a instance variable
final CollectionReference firestoreInstance =
FirebaseFirestore.instance.collection('course');
void _loadUserData() async {
await firestoreInstance.doc(documentID).get().then((event) {
// you can access the values by
print(event['isDOne']);
print(event['lastViewedOn']);
print(event['lectureNo']);
print(event['videoDescription']);
print(event['videoUrl']);
});
}
call the _loadUserData() function whenever you need to fetch the data.

How to get cloud firestore document unique Id before adding data to cloud firestore as Realtime database

We can get pushed Key in realtime database before adding data but in cloud firestore I could not find any method to find unique key before adding data.
String uniqueKey = ref.push().getKey();
So I am doing two operation add and then update .If I can get unique key before adding data to firestore I can do it one operation just add with unique key included in the document.
Currently I am doing like this.
Collection Reference
final sitesRef = FirebaseFirestore.instance
.collection('book_mark')
.doc(getUserId())
.collection("link")
.withConverter<SiteModel>(
fromFirestore: (snapshots, _) => SiteModel.fromJson(snapshots.data()!),
toFirestore: (siteModel, _) => siteModel.toJson(),
);
Add document then get document Id from response then update the document with document Id.So if update operation is failed somehow I could not access the document anymore. So it will create a problem down the line.
Future<String> addSiteFireStore(SiteModel siteModel) async {
try {
DocumentReference<SiteModel> response = await sitesRef.add(siteModel);
final Map<String, dynamic> data = <String, dynamic>{};
data['docId'] = response.id;
sitesRef.doc(response.id).update(data);
_logger.fine("Link added successfully");
return "Link added successfully";
} on Exception catch (_) {
_logger.shout("Could not add link.Please try again");
return "Could not add link.Please try again";
}
}
Is there any way to get the document Id beforehand?
Thanks in advance.
You can get a new document reference without writing to it by calling doc() (without arguments) on a CollectionReference. Then you can get the id property from the new document reference, similar to how you call getKey() on the new RTDB reference.
So:
final newRef = FirebaseFirestore.instance
.collection('book_mark')
.doc();
final newId = newRef.id;
Also see the FlutterFire documentation on CollectionReference.doc().

Flutter firestore write data with specific key

I want to upload some data to Firestore but I can't figure out how to set specific key to data. I found this was discussed here before but with old Firebase database, now syntax is different.
Future<void> writeProfileData(Map<String, dynamic> profileData) async {
await _databaseReference
.collection('profile')
.add(profileData)
.catchError((error) => print(error.toString()));
}
Now my data key is autogenerated and I want to have soething like .key(profileData['uid'])
Thanks a lot.
You could use the following syntax:
Future<void> writeProfileData(Map<String, dynamic> profileData) async {
var ref = Firestore.instance.document('profile/profileData');
ref.setData(profileData);
}

How do I get the surrounding data related to my userId using flutter and firebase

While using flutter I am able to successfully get the UserId, however I want to be able get more user data (using the UserId)
Surrounding Information:
With the userId how would I go about printing the users; name bio, membership... etc?
Since you are using Realtime Database, then to get the other data, you can do the following:
db = FirebaseDatabase.instance.reference().child("Users");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values);
print(values["name"]);
});
});
First add a reference to node Users then use the forEach method to iterate inside the retrieved Map and retrieve the other values.
Try like this :
Future<dynamic> getWeightinKeg() async {
final DocumentReference document = Firestore.instance.collection('you_collection_name').document(user_id);
await document.get().then<dynamic>(( DocumentSnapshot snapshot) async {
final dynamic data = snapshot.data;
print(data['name'].toString())
//Do whatever you want to do with data here.
});
}
getUsers() async {
//here fbPath is reference to your users path
fbPath.once().then((user){
if(user.value !=null){
Map.from(user.value).forEach((k,v){
//here users is List<Map>
setState((){
users.add(v);
});
}
}
});
}
//Or
getUsers() async {
//here fbPath is reference to your users path
//and userListener is StreamSubscription
userListener = fbPath.onChildAdded.listen((user){
//here users is List<Map>
setState((){
users.add(Map.from(user.snapshot.value));
});
});
}
//and cancel in dispose method by calling
userListener.cancel();

Firebase Realtime Database Query All Items in Flutter

I'm trying to get all the stored items inside the firebase realtime database and i'm not able to get them. Here the function that i'm using. I want to get all the keys stored inside the bdd(attached a screenshot of the bdd). The size of the returned items is 0 always.
Future<int> getEntriesNumber() async {
final response = FirebaseDatabase.instance
.reference();
var entries = [];
response.onValue.forEach((v) => entries.add(v));
print("getEntries $entries");
return entries.length;
}
Bdd Data
Thank you!
Solved with this:
DataSnapshot response = await FirebaseDatabase.instance
.reference().once();
print(response.value.toString());
You can solve with something like this:
final databaseReference = FirebaseDatabase.instance.reference().child('//hereTheCollectionName');
databaseReference.once().then((DataSnapshot snapshot) {
//snapshot.value will contain each register in your database.
});
You should use async/await to wait for all registers.

Resources