filtering data from firebase flutter - firebase

I'm new in Flutter
I`m get the data from Firestore DB and show it as a ListTile.
Code on the pic
enter image description here
and here
enter image description here
Screenshot from app here
enter image description here
I save userID for each document in DB.
How can I filter and show only the active user's data?
I need the simplest and freshest solution.
userID will be hidden later
files with code here

Hi There I would filter based on userId. Lets assume you want to get favourite user places, this user places will be a sub collection of the users one. Therefore I will do my filter as follow:
'''
// Get User Favourite Places.
Future<List<UserFavPlaces>?>? getUserFavouritePlaces(
{required String userId}) async {
final userFavouritePlaces = await FirebaseFirestore.instance
.collection('users')
.doc(userId)
.collection("FavouritePlaces")
.get();
if (userFavouritePlaces.docs.isNotEmpty) {
try {
return userFavouritePlaces.docs
.map((docs) => UserFavPlaces.fromJson(docs.data()))
.toList();
} catch (e) {
print(e.toString());
}
} else {
return null;
}
}
'''

Related

Firebase Document Fields are getting Deleted

For some time now, I have noticed that the fields of some of my firebase documents get deleted, even though I do not delete them or write any logic on my app to delete fields of a document or a document itself. This is a picture that shows a document on my firebase project, which has its fields deleted on its own.
The firebase project is connected to my flutter app, but I have not written any delete functionality.
I only update the fields occasionally with recent data.
Please, who has any idea of what's happening?
Edit
This is how I update the documents of my user collections
Future<String?> submitUpdate(User user) async{
CollectionReference userCollection = firestore.collection('users');
String? uid = await secureStorage.read(key: 'uid');
try{
//updates user doc in users collection
await userCollection.doc(uid).update(user.toMap());
return "Success";
}catch(e){
return null;
}
This is how i create the user document in the users collection.
Future<String?> saveUserCredentials(User user) async{
CollectionReference users = firestore.collection('users');
String? uid = await FlutterSecureStorage().read(key: "uid");
try{
//creates a user doc in the users collection
await users.doc(uid).set(
user.toMap()
);
return "Success";
}catch (e){
print(e);
return null;
}
I have a User model that defines the user object.
If you want to set some fields of a document, but keep existing fields, use set with SetOptions(merge: true):
FirebaseFirestore.instance
.collection(...)
.doc(...)
.set({'field1': value1, 'field2': value2}, SetOptions(merge: true));
Without this, the existing fields that are not listed in set will be not be kept, probably this happened to you.

Flutter & Firebase- How to allow only 1 account per device

I am trying to only allow the user to make 1 account on the device so when he makes an account and signs out, and then trys to make a new account it will not make the account and say this device already has an account.I got the device id so far but I dont know what to do now.
create a table in your database where the combined columns: userid (from new account) and deviceid are unique.
use device_info package to get unique device id
method get device id
Future<String> getDeviceId() async {
var deviceInfo = DeviceInfoPlugin();
if (Platform.isIOS) {
var iosInfo= await deviceInfo.iosInfo;
return iosInfo.identifierForVendor; // on iOS
} else {
var androidInfo = await deviceInfo.androidInfo;
return androidInfo.androidId; // on Android
}
}
What I would do is use the unique device id and in firestore create a document in the user collection whose document id is the device id, then to verify that the id already exists it would be to use the following code
FirebaseFirestore.instance
.collection('users')
.doc(idDevice)
.get()
.then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('Document data: ${documentSnapshot.data()}');
} else {
print('Document does not exist on the database');
}
});

How to get Firestore document specific data Flutter

When I press a button I want to get that email address for my Text widget.
You can try the following:
void _onPressed() {
Firestore.instance.collection("users").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
print(result.data["email"]);
});
});
}
This will retrieve all the emails inside the collection.
If you know the document id, then you can do the following to retrieve one email specific to the document id:
void _onPressed() async{
var firebaseUser = await FirebaseAuth.instance.currentUser();
Firestore.instance.collection("users").document(firebaseUser.uid).get().then((value){
print(value.data["email"]);
});
}
The above works assuming you have the currentuserid as a document id.
You can use the where function if you know the email address you are looking.
Firestore.instance.collection('users').where('email', isEqualTo: 'point#gmail.com');

How to delete a subcollection from firestore flutter

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.

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

Resources