How to get specific data from firebase with Flutter? - firebase

(EDİT)
I am getting error in below code, what I want to do is only get data of followed users, users are in a different collection, shared content is in a different collection, and
I'm getting an error on the 4th line, I hope I explained it correctly, I would appreciate if you could help.
Errors I get:
The getter 'data' isn't defined for the type
'Stream<QuerySnapshot<Map<String, dynamic>>>'.
Try importing the library that defines 'data', correcting the name to
the name of an existing getter, or defining a getter or field named
'data'.
My Code:
stream: FirebaseFirestore.instance.collection('posts').orderBy('datePublish',descending: true).snapshots().map((event) {
List following = [];
var userSnap = FirebaseFirestore.instance.collection("users").snapshots();
if(Provider.of<UserProvider>(context).getUser.following.contains(userSnap.data["uid"])){
following.add(event);
return following;
}
return following;
}),
userSnap.data, data is not defined!

Related

How to get document id from firestore

I'm trying to get my every document id in of my collection "meinprofilsettings". But I'm a bit struggling with that so maybe anyone can help.
First here's my code:
List<String> alluserids = [];
getHashtags() async {
final ref = FirebaseFirestore.instance;
QuerySnapshot snapshots = await ref.collection('meinprofilsettings').get();
for (QueryDocumentSnapshot idofuser in snapshots.docs) {
allVideoHastags.addAll(idofuser.id);
}
}
And then here's the error I get:
The argument type 'String' can't be assigned to the parameter type 'Iterable'.
This is a screenshot of my database:
I I just want every id of of every doc inside the list alluserids.
Perhaps you want to change this
allVideoHastags.addAll(idofuser.id);
To this:
alluserids.add(idofuser.id);
addAll method receives an Iterable as parameter. You want to add a single value so you should use .add
Also, you could use the .map method instead of for in:
allVideoHastags.addAll(snapshots.docs.map((idofuser)=>idofuser.id));
The behavior behind the last statement is that map returns an Iterable which has a value for each value that the base Iterable (in this case, your docs) contains.
In this case, the base iterable is snapshots.docs and our mapping returns Iterable<String> as we're returning every doc id. Hope this is enough for helping

Flutter listen to one document change using provider

I have seen examples of listening to document changes in streambuilder, but is it possible to use it in providers? I want to listen to changes in the document in userinfo collection.
Here is my code:
in databaseservice.dart
Stream <DocumentSnapshot> get info{
return userinfo.doc(uid).snapshots();
}
In main
return MultiProvider(
providers: [
StreamProvider<DocumentSnapshot>.value(
value: DatabaseService().info
), // other providers
In wrapper where I need to see the change:
final info = Provider.of<DocumentSnapshot>(context).data();
However, I'll first get error:
The method 'data' was called on null.
Receiver: null
Tried calling: data()
And later, the info variable is giving me null instead of a map.
I want to let users input their name and age after their first signup, but not when they sign in. So my idea is that when users sign up, there will be a new document in the collection, "userinfo", which sets their age and name as null at first.
Then the wrapper checks if the name is null. If null, it will turn to the gather information page. If it has a value, it will turn to the home page.
Could anyone tell me where I am doing wrong with my document snapshot thing, or have a better idea to implement this?

How to filter field value and send data into the firestore collection?

In the firestore collection named 'doctor' there are different fields including the field 'role'. I want to add the doctors into firestore with a role named doctor. How can I do this? Following is the code that successfully adds data into the database. If you can, tell me the way to add data with a specific field name. Thanks in advance.
service.ts
create_Newdoctor(Record){
return this.firestore.collection('doctors').add(Record);
}
component.ts
CreateRecord(docForm: NgForm){
let Record = {};
Record['fullName']=this.fullName;
Record['email']=this.email;
this.DoctorService.create_Newdoctor(Record).then(res=> {
this.fullName="";
this.email="";
console.log(res);
this.message = "Added";
}).catch(error=>{
console.log(error);
});
}
Notice that Record is a javascript object, and how you create a document in Cloud firestore, is by passing an object with all the filled attributes into the add method like what you did in service.ts, and how you pass in an attribute is via Record[ATTRIBUTE_NAME] = ATTRIBUTE_VALUE
Hence I believe what you need to just to add in the line Record[‘role’] = “doctors” into component.ts

Removing specific map/object from array in firebase

I'm experimenting with arrays and maps/objects in firestore. I wondered how can I remove a specific map from the array.
I tried something like this:
await Firestore.instance.collection('users').document(interestedInID).get().then((val){
return val.data['usersInterested'].removeWhere((item)=>
item['userID'] == userID
);
}).catchError((e){
print(e);
});
but I get this error in terminal:
Unsupported operation: Cannot remove from a fixed-length list
I don't really understand what it means. I did some googling and fixed-length list is exactly what it says. It's a list that has a fixed length and it can't be changed, but fixed-length list has to be declared explicitly. Growable list on the other hand doesn't need to be declared.
I haven't declared the fixed-length list in my firestore, yet it keeps saying that I can't remove elements from it. I can add / push elements however and remove them using:
'key': FieldValue.arrayRemove([value])
but I can't figure out how to remove the element based on a specific condition. In this case an userID.
Any suggestions?
Thanks a lot!
Figured it out.
await Firestore.instance.collection('users').document(interestedInID).updateData({
'usersInterested': FieldValue.arrayRemove([{}.remove(userID)])
});
I'm not sure, but I think get() simply allows you to read the document, but doesn't allow to make any changes to it.
Anyways, now it works
This may be a workaround:
You fetch your specific Array with key: values from Firebase
Put that in a temporary reference List in dart
Remove your specific Map from the reference List, like you did before
Update data in Firebase like so:
// make a reference List
List<Map> _modifiedUsersInterested = List();
// ... (fetch your Array first from Firebase, put those items in the reference List)
// remove the right Map from the reference List
_modifiedUsersInterested.removeWhere((item) => {
item['userID'] == userID
});
// set the reference List as your array in Firebase
await Firestore.instance
.collection('users')
.document(interestedInId)
.updateData(
{'usersInterested': _modifiedUsersInterested}
);

Unable to resolve flow annotation error when using immutablejs records and calling update on one

I see the following record type code:
type AppProps = {
+fetches: Map<string, number>,
};
export const makeApp: RecordFactory<AppProps> = Immutable.Record({
fetches: Immutable.Map()
});
export type App = RecordOf<AppProps>;
Now I have a call that uses the record's update function:
const state = makeApp({});
const result = state.update('fetches', val =>
val.set(action.meta.actionBase, 1)
);
All unit tests pass, behaviour is good, but I get a flow error:
Error:(40, 18) Missing type annotation for T. T is a type
parameter declared in RecordInstance [1] and was implicitly
instantiated at call of method update [2].
I have an idea what is going on here, but I don't know flow well known to actually fix this, or even come up with a workaround. Please help!
ImmutableJS version "immutable": "^4.0.0-rc.12",
Flow is asking for a concrete type argument for T, which is defined in the update function of state.
Here's another example of a cause and fix of this error message:
Missing annotation error
Fixed
If you provide the type signature of state.update, I may be able to provide more information.

Resources