this is the function i used to add a new document to a collection, but now i want to use it to add new data to the current user.
CollectionReference db = FirebaseFirestore.instance.collection('events');
Future<void> addEvent(EventsModel eventModel) async {
Map<String, dynamic> data = {
"eventName": eventModel.eventName,
"date": eventModel.date,
"gateopens": eventModel.gateopens,
"ticketPrice": eventModel.ticketPrice,
"quantityofticket": eventModel.quantityofticket,
"descriptionevent": eventModel.descriptionevent,
"locationevent": eventModel.locationevent,
"imagesUrl": eventModel.imagesUrl,
"category": eventModel.category,
"isSale": eventModel.isSale,
"isPolular": eventModel.isPopular,
};
await db.add(data);
}
Related
I have this function which is called when I push an Upload Button. It should create a collection in Firestore called userPosts with postId, ownerId, and mediaUrl. Everything is working except username because I have to take it from another collection in Firestore called users. So I have this error: Unhandled Exception: Invalid argument: Instance of 'Future <String>' How can I fix this? Thanks!
final userRef = FirebaseFirestore.instance.collection('users');
final postsRef = FirebaseFirestore.instance.collection('posts');
createPostInFirestore({required String mediaUrl}) {
postsRef.doc(user!.uid).collection("userPosts").doc(postId).set({
"postId": postId,
"ownerId": user!.uid,
"username": userRef.doc(user!.uid).get().then((snapshot) {
return snapshot.data()!['username'].toString();
}),
"mediaUrl": mediaUrl,
"timestamp": timestamp,
"likes": {},
});
}
the get() and set() methods are asynchronous ( needs time to resolve ), so we need to make the function asynchronous with the async keyword, then wait to get the username, after that, wait to update the data with set().
try this:
final userRef = FirebaseFirestore.instance.collection('users');
final postsRef = FirebaseFirestore.instance.collection('posts');
Future<void> createPostInFirestore({required String mediaUrl}) async {
final username = await userRef.doc(user!.uid).get().then((snapshot) {
return (snapshot.data() as Map<String, dynamic>)!['username'].toString();
});
await postsRef.doc(user!.uid).collection("userPosts").doc(postId).set({
"postId": postId,
"ownerId": user!.uid,
"username": username,
"mediaUrl": mediaUrl,
"timestamp": timestamp,
"likes": {},
});
}
then on the onPressed or the method which will execute this function, you need to wait for it also like this:
onPressed: () async {
await createPostInFirestore("your string URL here");
}
now it will work fine
I'm new to flutter and I'm trying to get the specific document's fields. I've saved auth id in firestore and using that auth ID in where query I'm trying to access that document and accessing displayName and storing it in userName variable but when i user Database.userName where i want to show this field it displays null on screen.
class Database {
static String? userName;
static void showDisplayName() async {
var collection = FirebaseFirestore
.instance
.collection('Users');
try {
var docSnapshot = await collection
.where("email", isEqualTo:AuthService().currentUser!.uid)
.snapshots().listen((event) { userName = event
.docs[0]['displayName'];});
}on FirebaseException catch (e){
print(e);
} catch (error){
print(error);
}
Map<String, dynamic> data = docSnapshot as
Map<String, dynamic>;
userName = data['displayName'];
}
}
and displaying that username in drawer
accountName: Text("${Database.userName}")
This is the code that im developing to get a collection from Firestore and store all its data in another map
onPressed: () async {
Map<String, dynamic> data = {};
await FirebaseFirestore.instance.collection('primary').get() .then((values) {
for (var I in values.docs) {
data.addAll(i.data());
}
print(data);
});
},
if I just print i.id, I will get all 9 ids that are available. But, by doing this to copy all the data from the map, when I print the Map data, Im only Storting the last value. Ive tried to use forEach but happened the same
You have to make data a List<Map<String, dynamic>> instead of Map<String, dynamic> so you can add values to it instead of overwriting it the whole time.
So do this:
onPressed: () async {
List<Map<String, dynamic>> data = {};
await FirebaseFirestore.instance.collection('primary').get().then((snapshots) {
for (var doc in snapshots.docs) {
data.add(doc.data());
}
});
print(data);
},
I have a collection users where every user has his own document. Now I want to create a subcollection to store more data related to a specific user.
So far my Code looks like this:
class DatabaseService {
Future isUserRegistered(String uid) async{
return await FirebaseFirestore.instance.collection('users')
.where('uid', isEqualTo: uid)
.get();
}
Future registerNewUser(email, password, uid) async{
return await FirebaseFirestore.instance.collection('users')
.doc(uid).set(
{
"email": email,
"password": password,
"uid": uid,
"token": -1,
"userGoal": false,
"userGender": false,
},
);
}
Future saveToRemote() async{
Map<String, dynamic> data = UserManager.userdata;
return await FirebaseFirestore.instance.collection('users')
.doc(data['uid'])
.set(data);
}
class UserManager {
static Map<String, dynamic> userdata = null;
}
How can I store data in a subcollection?
EDIT
I created a new save function but instead of storing data in a subcollection in the document with the current uid, firestore creates a new document named 'uid'. How to fix that?
Future saveInSubcollectionToRemote() async{
Map<String, dynamic> data = UserManager.userWeights;
return await FirebaseFirestore.instance.collection('users')
.doc('uid')
.collection('weights')
.doc(data['userWeight'])
.set(data);
}
Saving to a subcollection is no different from saving to a top-level collection. You build a path to the CollectionReference under the user's document and call add like this:
FirebaseFirestore.instance
.collection('users').doc(uid)
.collection('subcollection').add(
{
"field": value,
},
);
I am trying to add my data in a textformfield which then saves to firestore, this includes the documentID. The data comes back as null or "" for some reason.
Below is my code:
final barcode = TextEditingController();
final price = TextEditingController();
final stock = TextEditingController();
final color = TextEditingController();
addData() {
Map<String, dynamic> theData = {
"Color" : color.text,
"Price" : price.text,
"Stock" : stock.text,
};
CollectionReference collectionReference = Firestore.instance.collection("products");
FirebaseFirestore.instance.collection("products").doc(barcode.text).set(theData);
collectionReference.add(theData);
}
I have tried making it async but still nothing, I want the data to be set when I click the done button which has a onpressed method calling the addData.
This is my data in firestore when I only set the data and not the ID:
You have to use await
addData() async { // ASYNC HERE
Map<String, dynamic> theData = {
"Color" : color.text,
"Price" : price.text,
"Stock" : stock.text,
};
CollectionReference collectionReference = Firestore.instance.collection("products");
await collectionReference.doc(barcode.text).set(theData, merge:true); // AWAIT HERE
or
CollectionReference collectionReference = Firestore.instance.collection("products");
await collectionReference.doc(barcode.text).updateData(theData); // AWAIT HERE
}
Also not sure why you both set and add theData? Use updateData() or set() with merge:true. The document will be created either way