Flutter Firebase how would I go about getting specific data from snapshot - firebase

I am currently using a realtime database for my application. I am having trouble reading specific user data from a snapshot.
My code:
final databaseReference = FirebaseDatabase.instance.reference();
void getData() {
databaseReference.once().then((DataSnapshot snapshot) {
Map<dynamic, dynamic> values = snapshot.value;
//print(snapshot.value['name']);
print('Data : ${snapshot.value}');
});
}
My database layout:
Users:
userId:
name: TEST
email: TESTEmail#gmail.com
bio: TESTBio
I want to be able to read the name of an individual with a specific userId (for example Bdhsaiweuy2731319238121shda), how would I go about doing so? Thank you for your time, I really appreciate it.

If you know their UID, you can look up that user directly with databaseReference.child("Users/Bdhsaiweuy2731319238121shda") and then read the data from there. Something like:
databaseReference.child("Users/Bdhsaiweuy2731319238121shda").once().then((DataSnapshot snapshot) {
print(snapshot.value['name']);
});

values is a variable of type map and it will contain all the retrieved data. If you want access only to the name value, then you need to iterate inside this map and use the get [] operator to get the value of the name. Example:
values.forEach((key,values) {
print(values["name"]);
String name = values["names"];
});
https://api.dartlang.org/stable/2.7.0/dart-core/Map-class.html

Related

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

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

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().

Post entrie map to Firestore with flutter

I'm attempting to post an entire map to Firestore using Flutter as follows:
Profile {
String studentFirstName;
String studentSurname;
String yearLevel;
String preferredHand;
Map<String, dynamic> background = {};
Profile({
this.studentFirstName,
this.studentSurname,
this.yearLevel,
this.preferredHand,
this.background,
)}
Future<bool> createStudent(String schoolId) async {
var newStudent = await db
.collection('schoolStudents')
.doc(schoolId)
.collection('students')
.add({
'studentFirstName': _profile.studentFirstName,
'studentSurname': _profile.studentSurname,
'yearLevel': _profile.yearLevel,
'preferredHand': _profile.preferredHand,
'background': {_profile.background},
}
}
However this fails with the below error message.
Unhandled Exception: Invalid argument: Instance of '_CompactLinkedHashSet<Map<String, dynamic>>'
Can someone let me know if you can post an entire map to Firestore and if not, the most appropriate way to.
As you say,
"Can someone let me know if you can post an entire map to Firestore and if not, the most appropriate way to."
So try this way to post data(example).
Map map=Map();
map ={"name":"abc","id":"1"};
Future<bool> createStudent(String schoolId) async {
var newStudent = await db .collection('schoolStudents') .doc(schoolId)
.collection('students')
.add({
'studentFirstName': _profile.studentFirstName,
'studentSurname': _profile.studentSurname,
'yearLevel': _profile.yearLevel,
'preferredHand': _profile.preferredHand,
'background': map,
}
The problem is that object you would like to add as background filed in Firestore is nested. This is because the background field of the Profile object is already a map from the beginning, so adding brackets ({}) around it in add method is creating Set of Map objects, and Set is not among of Types in Firestore. This is the reason of the error.
So it seems that it's enough to remove brackets ({}) from add method:
Future<bool> createStudent(String schoolId) async {
var newStudent = await db
.collection('schoolStudents')
.doc(schoolId)
.collection('students')
.add({
'studentFirstName': _profile.studentFirstName,
'studentSurname': _profile.studentSurname,
'yearLevel': _profile.yearLevel,
'preferredHand': _profile.preferredHand,
'background': _profile.background,
})

How to find the id of a document if you only know the data of one field (firestore)?

I have a problem. I have to get the automatically generated id of a document with the help of the data of a field which is in the document from which I have to find out the id.
To make it more logical, an example: As you can see on the screenshot, I have the 'seller' collection, which in turn has different documents that contain different data. The app only knows what the name is, but not from which field it takes the name (e.g. name: 'Paul'). The task is that the app now has to find out which document the name Paul comes from. In this case it would be '
4wHJZ3I2hAqbCFP0323A '.
I saw on the internet that there is a filter option for firestore, but I don't know how I can use this to get the ID of the document. Can anyone help me?
You need to do the following:
final firestoreInstance = FirebaseFirestore.instance;
firestoreInstance
.collection("seller")
.where("name", isEqualTo: "Paul")
.get()
.then((value) {
value.docs.forEach((result) {
print(result.id);
});
});
with async/await:
getData() async {
final firestoreInstance = FirebaseFirestore.instance;
final result = await firestoreInstance.collection("users").where("name", isEqualTo: "Paul").get();
result.docs.forEach((result) {
print(result.id);
});
});
result.id will give you the document id where name = Paul.

Resources