How can i show images to limited users in flutter - firebase

I want to show my post to my followers only how can I implement that here is my code.
here is the structure of my user collection
here is the collection of posts by user
final model.User userProvider = Provider.of<UserProvider>(context).getUser;
StreamBuilder(
stream: FirebaseFirestore.instance
.collection(post_collection)
.orderBy("datePublished",
descending:
true)
.snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
return ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) =>
PostCard(snap: snapshot.data.docs[index].data()));
}),

My logic to approach this problem would be:
If I am a user, I should be able to see the post of people I follow, so the source of posts that are visible to me would arrive only from the list of people I follow. Create this list as an attribute of users in their database record. Every time the user follows someone, that someone is added to this list.
So if you want your posts to be seen only by your followers, as soon as someone follows you, your account would be added to the list of people they follow. Thus your account becomes just another source of accounts from which that particular follower receives post updates from.
You could implement the logic to receive posts only from the list of people a particular user follows. This way only your followers will be able to see your posts.

Related

The argument type 'User?' can't be assigned to the parameter type 'Future<Object?>?'

With reference to the recent changes regarding FirebaseUser to User. FirebaseAuth.instance.currentUser() is not found at all (while throughing error "The expression doesn't evaluate to a function, so it can't be invoked." The solution to that however was to simply remove the paranthesis as FirebaseAuth.instance.currentUser. But now we have another error that it isn't a future type i.e "The argument type User can't be assigned to the parameter type Future<Object?>?". Following is my code block.
return FutureBuilder(
future: FirebaseAuth.instance.currentUser,
builder: (ctx, futureSnapshot) => ListView.builder(
reverse: true, // So that 1st message goes to last.
itemCount: chatDocument.length,
itemBuilder: (ctx, index) => MessageBubble(
message: chatDocument[index]['text'],
isMe: chatDocument[index]['userId'],
),
),
);
In the above code block I intend to provide future to my `FutureBuilder`. In summary previously `FirebaseUser` object did return a future, but probably `User` doesn't anymore. How may I handle this case? Thanks in advance.
I don't typically do that with a FutureBuilder. Once you have a user, you don't need to async it.
final FirebaseAuth_auth = FirebaseAuth.instance();
final User? user;
user = _auth.currentUser;
Then, if user != null ....create your ListView else, return a CircularProgressIndicator or whatever.
Look up Net Ninja for some nice videos for getting yourself set up with all that, just having a stream based on userChanges() for your project. More robust setup.

Flutter: Identify if there are documents in a firebase collection

I want to post data to a series of collections and documents one within the other,
CollectionReference data = FirebaseFirestore.instance
.collection('Data')
.doc(user)
.collection('First')
.doc(category)
.collection(time);
data.add({'element': 'field'});
but when I try to do it, the names of the dynamic names appear in italics, it would not be a problem if it were only a variation of the font style, the problem is that when I try to know if there is data in the collection First it shows me that there is nothing
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Data')
.doc(user)
.collection('First')
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return Icon(Icons.check);
}
return Icon(Icons.error);
},
);
}
flutter: null
It is necessary to separate by first, second, third, etc and each of these must have separate different categories and in each category must have its time
Firebase looks like this
Data -> S6W4kb1dKycD060v47FFs0i528Q2 -> First -> post -> 19:00
Only if I add an item directly from the Firebase console does it recognize that items exist
In your call fragment...
CollectionReference data = FirebaseFirestore.instance
.collection('Data')
.doc(user)
.collection('First')
.doc(category)
.collection(time);
...NONE of the .collection() and .doc() create anything - they are just extending the refPath of the underlying reference i.e. Data/{user}/First/{category}/time is the collection you will add to. When you FINALLY execute data.add({'element': 'field'}) a SINGLE document with contents (and unspecified Id) {'element': 'field'} is added.
It is helpful to remember that in Firestore, "collections" are not a physical identity; they are a convenient part of a structured path to a document. For example, in
TopLevel/document1/NextLevel/document2/NextNextLevel/document3/NextNextNextLevel/actualDocument
NONE OF TopLevel, document1, NextLevel, document2, NextNextLevel, document3, or NextNextNextLevel need to exist - which is why they show in italics in the console.

how to get data from firestore sub-collection

i have a firestore database in which i have "Singer" then inside every singer there is a sub-collection of "Song List" for every singer. i am able to get data from main collection but not from sub-collection. can you guys help?
stream Builder
StreamBuilder(
stream: Firestore.instance.collection('singers').snapshots(),
ListView.Builder
ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) => SingleChildScrollView(
this is where i want to show data from sub-collection
Text(
snapshot.data.documents[index]['name'],
style: TextStyle(
fontSize: 20, color: Colors.red[500]),
)
Database
You can get the data from the collection by accessing the subcollection inside the document like this
Firestore.instance.collection('singers').document('aryana sayeed').collection('song list').snapshots()
or
Firestore.instance.collection('singers/aryana sayeed/song list').snapshots()
You can read it like this:
Firestore.instance.collection('singers').snapshot().listen((val)=>{
val.documents.forEach((doc)=>{
doc.reference.collection('song list')
.getDocuments().then((res)=>{
res.douments.forEach((d)=>{
print(d.data);
})
})
})
});
Now this gives you a stream to all docs of collection singers and thier subcollection
To clarify what you are saying: you want a list of all the songs from all the singers,
Easy-Peasy. CollectionGroup is your friend.
I don't use your environment, but I can see that:
StreamBuilder(
stream: Firestore.instance.collectionGroup('song list').snapshots(),
is the start you need. collectionGroup treats all sub-collections with the name 'song list' as one collection.
NOTE (because this always comes up)
Each documentSnapshot returned include a field 'refpath' - which is a string with the entire path to that specific document. You can trivially parse the string to find the parent document(s) or collections(s). For example, a particular song with have in it's refPath ".../singers/{singerID}/songlist/{songID}"
btw, I HIGHLY HIGHLY HIGHLY recommend AGAINST using the singer name as the document ID. Queries are generally of fields, not documentID's, so it won't help your code find the artist, and they are neither unique enough nor randomly distributed enough to be efficient. Let Firestore generate unique documentID's for you, and put the artist name in a field.

Get all documents from collection in firestore

I'm trying to get all posts from my 'instagram' clone app. This is the path I have in firestore: posts > (unique ownerId) > userPosts > (unique postId)
How can I retrieve all posts using a stream builder? I tried doing so with
body:
StreamBuilder<QuerySnapshot>(
stream: postsRef.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
List<Post> posts = snapshot.data.documents.map((doc) => Post.fromDocument(doc)).toList();
return ListView(children: posts);
},
)
I want to display only the posts' pictures in a stack of cards.
You can't use wildcards with listeners in Cloud Firestore. You need to name the specific document and collections in the path. So, if your (unique ownerId) is unknown at the time of the query, you will not be able to know anything about the documents changing in its subcollections.
As an alternative, on a backend you control, you can list subcollections of a document, then query those documents. Or, you can use a Cloud Functions trigger and notify interested client apps (maybe with Cloud Messaging) as changes happen.

Flutter Firestore Two StreamBuilders of the Same Document Count as 2 Reads?

In my Flutter app, will it count as two reads from Firestore if I have two nested StreamBuilders reading from the same document? Or is it cached in a way that it will only count as one read?
Here's an example of what I'm talking about.
StreamBuilder(
stream: Firestore.instance.document(path).snapshots(),
builder: (context, asnap){
//Some nested widgets...
return StreamBuilder(
stream: Firestore.instance.document(path).snapshots(),
builder: (context, asnap){
return MyWidget();
},
);
},
);
As far as I know, the Firestore client deduplicates these listeners. So if a first listener is already active for the exact same data, it won't attach a second listener. So you won't be charged for two reads, but (possibly even more important to your users) the data will only be transferred once.

Resources