Retrieve from Firestore just the UserID in the array Flutter - flutter

Hello I have a stream Builder in firestore which display a list of user.
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('Users').where('recentUser',arrayContainsAny: ['userId'])
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CupertinoActivityIndicator()
);
}
final data = snapshot.data!.docs;
in the Firestore collection I have a document which have userId Field and an array of user ID.
I am trying to retrieve the list of user and for a specific user I want to retrieve just the user that the id is in the array recentUser
As per above example I have tried to user .where('recentUser',arrayContainsAny: ['userId'])
but unsuccesfully...
Any idea?

try replacing ['userId'] with [userId] or ['$userId'] depending on type

Related

how to get document id index on firestore with flutter onTap method

I am trying to get the document ID. I don't know if it is the right way, but until now I could manage to get all the IDs.
Then I am trying to get the document ID index so I can open the category with onTap and show the category products.
I have tried with map, forEach, etc... but nothing.
return Scaffold(
body: StreamBuilder(
stream: firestore.snapshots(),
builder:(context, snapshot){
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());{
final document = snapshot.data?.docs;
return ListView.builder(
itemCount: document?.length,
itemBuilder: (context, index) {
return Center(
child: Column(
children: [
InkWell(
onTap: (){
FirebaseFirestore.instance.collection('prova').get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.map((doc) {
print(doc.id);
var docId = doc.id;
Navigator.push(context, MaterialPageRoute(builder: (context)=>
CategoriesPage(document: document[index]['name'], docId: docId)));
});
});
As I mentioned in my comment, the way FireStore allows you to store data is alternating between collections and docs. That's to say you can't put another doc into a doc, and another collection within a collection. You can only put docs in a collection, and then subcollections within a doc, etc, etc.
I'm unaware of your data structuring needs, however I'd suggest something like this:
When a user creates a category, simply add it to their doc, and then any products within the category could be placed into a sub-collection under that category. Let me know if that could work for you.

Combine two stream-queries in flutter

I want to create a streambuilder to download multiple user-profiles from firebase. But to know which users are needed I have to get the user-ids at first, these are stored in an array. So I created a method to download the array and after this is done the streambuilder loads the user-data for each user-id from the array. Here's the code:
Method to get the array (executed in initState()):
Stream<QuerySnapshot> stream() async* {
job = Job.fromJson(await FirebaseFirestore.instance
.collection("jobs")
.doc(widget.jobId)
.get());
applicants = job.applicants;
await FirebaseFirestore.instance
.collection('users')
.where('uid', whereIn: applicants)
.snapshots();
}
And the streambuilder in the scaffolds' body:
body: isLoading
? Center(child: Container(child: CircularProgressIndicator()))
: applicants.isEmpty
? Center(
child: Text("no values"),
)
: StreamBuilder<QuerySnapshot>(
stream: stream(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else { xy }
So my question is if there's a possibility to combine the first method and the stream. Because at the moment the user can't get any update if an application is withdrawn while using the screen.

Flutter Fire Store - Assigning individual document fields to variables

I'm attempting to show a user's profile image on their home page by pulling the user's 'imageUrl' from their Fire Store document. I already have the app setup to where the user can upload a new image which updates the 'imageUrl' in Fire Store, but I don't know how to have the 'imageUrl' as a variable so I can show it on the app screen.
I've been reading documentation online but It seems over simplified or out of date. I've tried using StreamBuilder, but it pulls the data from every user in the database instead of for a single user. I just need to know how to pull this one value and use it as a variable in my dart code using "getString()" with a document reference or the collection reference I already have, thank you.
class _UserPageState extends State<UserPage> {
User user = auth.currentUser!;
final CollectionReference collectionReference = FirebaseFirestore.instance.collection('users');
// Get profileImageUrl from users userDoc
String imageUrl = 'test'; // this should be the users imageUrl
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'${user.email}'), // this is being pulled from authentication not firestore
),
body: Center(
child: Column(
children: [
// --------------------------- I tried using a stream builder here ---------------------
StreamBuilder(
stream: collectionReference.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Text(
'Something went wrong.'); // A: use incase the data does not load
}
final data = snapshot.requireData;
return ListView.builder(
shrinkWrap: true,
itemCount: data.size,
itemBuilder: (context, index) {
return Text(
// A: Stream builder will update with all of the users email addresses, I want this for one user exclusively
'My email is ${data.docs[index]['email']}');
},
collection('users')
.where("uid", isEqualTo: uid)
.snapshots(),
To filter the data in firestore collection use "where". Store the user uid in offline and query it by where using the stored uid
You can use the following function to get single data from stream.
Stream<UserModel> getSingleStreamData({String? uId}) {
return ref!.where(CommonKeys.id, isEqualTo: uId).snapshots().map((value) => value.docs.first.data());}

How Can I Get Document name from AsyncSnapshot<QuerySnapshot>

The Goal
Get a document name from AsyncSnapshot<QuerySnapshot>
What I Did
In this collection users there is many documents which name is uid.
Using FutureBuilder and got AsyncSnapshot<QuerySnapshot>.
FutureBuilder(
future: FirebaseFirestore.instance
.collection("users")
.where('type', arrayContainsAny: ["Game", "Movie"])
.get(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
if (snapshot.connectionState == ConnectionState.done) {
String uid = ...... // Want to get document id (= uid)
By using this snapshot, it was possible to get fields of each documents.
But ofcourse these don't include their own name.
How can I get document id from AsyncSnapshot<QuerySnapshot>?
snapshot.data!.docs can contain zero, 1 or more documents matching the criteria. This is a list of document snapshots.
So for example the first result can be in snapshot.data!docs[0]. From here to get the document id (in your case uid) simply use snapshot.data!docs[0].id.

Firestore Flutter How Sort Data using int fields

Hello i have a firestore db with structure
Root
.....Oder
.........Xyz1
______T:1
.........Xyz1
______T:1
when i get the data i want it to sort automatically in desending oder using the int value stored in 'T'
T is unique for every document
child: StreamBuilder(
stream: Firestore.instance.collection("Oder").snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return new Text('Loading...');
}
return new ListView(
reverse: true,
children: snapshot.data.documents.map((document) {
return new ListTile(
title: new Text(document['T'].toString()),
);
}).toList(),
);
},
),
This is my code here
I also have the same value of T as String as each document name so sorting with that gave me 1,10,11,2,3...
So i need to get sorted with the int value stored in T
This is
You can get the data with this line:
CollectionReference collectionReference = Firestore.instance.collection("data-collection");
But , you can get the ordered data with:
Query collectionReference = Firestore.instance.collection("data-collection").orderBy('field');
orderBy should returns a Query, you can no longer store it as a CollectionReference.