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);
}
Related
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");
});
});
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.
I am currently learning how to use Firebase and it is not too intuitive to me, yet. Basically, I would like to retrieve only the last document in my Cloud Firestore collection and save it as a Map<String, dynamic>. Here is my code:
final _firestore = FirebaseFirestore.instance;
Future<Map<String, dynamic>> fetchData() async {
Map<String, dynamic> collection;
try {
QuerySnapshot<Map<String, dynamic>> data = await _firestore
.collection('collection')
.orderBy('timestamp', descending: true)
.limit(1).get();
collection = data;
} catch (e) {
print(e);
}
return collection;
}
As of my understanding, the QuerySnapshot returns multiple DocumentSnapshots. I thought if I limit it to 1 and sort it by the generated timestamp I would be able to only get the last added document. However, I am unable to save my QuerySnapshot as a Map<String, dynamic> and could not find a way to make it work.
Many thanks in advance to those taking their time answering to this!
Try this:
collection = data.docs.first.data() as Map;
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().
so am new using firestore to store data. at the moment i need to delete data already saved in the Firestore through my App. I have tried
Future<void> removeDocument(String id, String userId){
return ref.document(userId).collection(userId).document(id).delete().whenComplete((){
print("DELETE DONE::");
});
}
But its not working.
The thing is I used the userId to save the user details
now I want to delete the data but it does not delete the data even though the print message shows in my Log.
The method below is how i add data to the Firestore
Future<void> addDocument(Map data, String userId){
return ref.document(userId).collection(userId).add(data);
}
void setupLocatorWorkout() {
locatorWorkout.registerLazySingleton(() => Api('workout_goal'));
locatorWorkout.registerLazySingleton(() => CRUDRemoteDataSource());
}
Api(this.path){
print("$path");
ref = _db.collection(path); // this is the base collection
}
please what am i doing wrong here?
Thank you!!!
Delete a User by UID:
void deleteUser(User user) async {
await db.collection(COLLECTION_NAME)
.document(user.uid)
.delete()
.then((_) {
print('User deleted.');
});
}
Don't forget to add import 'dart:async'; at the top
The answer is you shouldn't.
According to the Firestore docs, you should not do this because:
While it is possible to delete a collection from a mobile/web client, doing so has negative security and performance implications.
However the link shows how it can be done frome some platforms.