I have created a chat with flutter and I need to use into my app, where 1group of user will chat with another kind of user group.
At the moment my chat is developed in this manner and I create record in firebase so:
CollectionReference addMessage = FirebaseFirestore.instance.collection('Messages');
Future<void> createMessageRecord() {
return addMessage
.add(
{ 'id': firebaseUser.uid,
'text': textMessage,
'timeStamp': DateTime.now().millisecondsSinceEpoch.toString(),
},
)
I retrieve them:
StreamBuilder(
stream: FirebaseFirestore.instance.collection('Messages').orderBy('timeStamp', descending: true).snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
I display them:
ListView.builder(
reverse: true,
padding: EdgeInsets.only(top: 15.0),
itemCount: snapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
final message = snapshot.data.docs[index];
final bool isMe = message['id'] == firebaseUser.uid;
return _buildMessage(message, isMe);
the chat works pretty good but all users of course will have the same chat.
What I want to do is limit the chat displaying just for the 2 users.
the first one who starts the chat and and second one who get.
At the moment I have created into firestore a collection called "Messages" and into I have the 3 documents id text timeStamp```
I dont know how to limit the displaying data just for this 2 users
Instead of having one single document for all of the messages create a document per conversaiton this way you will only retrive the corresponding messages.
Also as mentioned on the comment by #Uni you shoudl be using realtime database also you can take a look at several examples on the web on how to accomplish that. for example
Related
I am currently developing a chatting page on my mobile application and was using Realtime Database to reduce costs. Not having much Realtime Database experience, I am running into issues developing a page for active chatrooms where each user has a document with their uid where there is an array of chats . How can I generate a list of the first names based on the items inside of the array of chats.
I realize it's best practice to show code you have tried, however, I have only used Firebase Firestore and have no idea where to start, considering the complexity of the structure
You can try this answer.
Here I have created StreamBuilder for getting data once. As I have provided, Stream outside of StreamBuilder means it will create a stream only once.
final _snap = FirebaseDatabase.instance
.ref()
.child(`users/${uid}`)
StreamBuilder<Event>(
stream: _snap.onValue,
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
DataSnapshot snap = snapshot.data as DataSnapshot;
List<dynamic> chatArray = snap.value['chats'];
List<String> firstNames = [];
for (var chat in chatArray) {
String firstName = chat[recepientFirstName];
firstNames.add(firstName);
}
return ListView.builder(
itemCount: firstNames.length,
itemBuilder: (context, index) {
return Text(firstNames[index]);
},
);
} else {
return Text('Loading...');
}
},
)
Found similar reference about this Questions so you can also visit these threads:
Thread1
Thread2
Thread3
I'm new to flutter, and now I'm creating an app which has a feed page, I'm using StreamBuilder + firestore to do this, the code is like this:
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('posts')
.orderBy('createdAt', descending: true)
.snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(
color: primaryColor,
),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) => Container(
child: createPostViewFromSnapShot(snapshot.data!.docs[index]),// it returns a widget
),
);
},
);
You can see from the code I didn't do pagination, I want to know when the code runs, it fetch all the post from firestore ? Or it will fetch data by block or something like pagination ?
I want to know if it's necessary to do pagination for StreamBuilder?
Avoid creating Widgets in Methods. That way you cause your App to
become I'm-performant. Because the Widget is not sat directly in the
Tree, but a method, every build that methods gets called, no matter
if the resulting widget would have to be actually be rebuilt.
That stream will not always emit events where data is not null. You will most likely get an exception for using snapshot.data! bang operator
Take a closer look at the documentation: https://firebase.flutter.dev/docs/firestore/usage/
FlutterFire provides support for dealing with realtime changes to
collections and documents. A new event is provided on the initial
request, and any subsequent changes to collection/document whenever a
change occurs (modification, deleted or added).
For what you are trying to achieve, it would be better to initially fetch a limited set of documents from your collection.
collectionReference.limit(42).get()
You can than fetch the next elements by using https://firebase.flutter.dev/docs/firestore/usage/#start--end-cursors
I'm trying to add chat functionality to my app (kind of similar to WhatsApp functionalities), using flutter and Firestore. The main structure on Firestore is to have 2 collections (I want the unread message count as well):
users: and each user will have a subcollection "chats" that will include all CHATS_IDs. This will be the main place to build home chat page (shows a history list of all chats) by getting the user chat list.
chats: a list of all chats and each chat document has a subcollection of messages.
My main issue is in building the home page (where a list of all user previous chats should appear). I get/subscribe the user chat subcollection, and for each chat ID listed in there I also subscribe for the chat itself in the chat collection (using the ID).
Here are screenshots of it in principle:
users collection:
chats coleection:
and here is the main screen of interest (principle from whatsapp screen):
What I'm doing is that I retrieve user's chat subcollection (and register a listener to it using StreamBuilder), and also for number of unread messages/last message and last message time, I subscribe to listen for each of these chats (and want to use each user last message time, status and his last presence in that chat doc to calculate the unread count) .
The problem is that Listview.builder rebuilds all items (initially and on scroll) instead of just the viewed ones. here is my code:
Stream<QuerySnapshot> getCurrentUserChats(userId) {
return FirebaseFirestore.instance
.collection(AppConstants.USERS_COLLECTION)
.doc('$userId')
.collection(AppConstants.USER_CHATS_SUBCOLLECTION)
.orderBy('lastMsgTS', descending: true)
.snapshots()
.distinct();
}
Widget getRecentChats(userId) {
return StreamBuilder<QuerySnapshot>(
stream: getCurrentUserChats(userId),
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data.docs.isNotEmpty) {
print('snapshot of user chats subcoll has changed');
List<QueryDocumentSnapshot> retrievedDocs = snapshot.data.docs;
return Container(
height: 400,
child: ListView.builder(
//childrenDelegate: SliverChildBuilderDelegate(
itemCount: snapshot.data.size,
itemBuilder: (context, index) {
String chatId = retrievedDocs[index].id;
print('building index: $index, chatId: $chatId');
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection(AppConstants.CHATS_COLLECTION)
.doc('$chatId')
.snapshots()
.distinct(),
builder:
(context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasData) {
print('${snapshot.data?.id}, isExist: ${snapshot.data?.exists}');
if (snapshot.data.exists) {
return KeyProxy(
key: ValueKey(chatId),
child: ListTile(
leading: CircleAvatar(
child: Container(
//to be replaced with user image
color: Colors.red,
),
),
title: Text('$chatId'),
subtitle: Text(
"Last Message received on: ${DateTimeUtils.getDateViewFromDT(snapshot.data.data()['ts']?.toDate())}"),
),
);
}
}
return SizedBox.shrink();
},
);
},
/*childCount: snapshot.data.size,
findChildIndexCallback: (Key key) {
print('calling findChildIndexCallback');
final ValueKey valKey = key;
final String docId = valKey.value;
int idx = retrievedDocs.indexOf(retrievedDocs
.where((element) => element.id == docId)
.toList()[0]);
print('docId: $docId, idx: $idx');
return idx;
}*/
),
);
}
return Center(child: UIWidgetUtils.loader());
});
}
After searching, I found these related suggestions (but both didn't work):
A github issue suggested thesince the stream is reordarable (github: [https://github.com/flutter/flutter/issues/58917]), but even with using ListView.custom with a delegate and a findChildIndexCallback, the same problem remained.
to use distinct.
But removing the inner streambuilder and just returning the tiles without a subscription, makes the ListView.builder work as expected (only builds the viewed ones). So my questions are:
Why having nested stream builders causing all items to be rebuil.
is there a better structure to implement the above features (all chats with unread count and last message/time in real-time). Especially that I haven't added lazy loading yet. And also with this design, I have to update multiple documents for each message (in chats collection, and each user's subcollection).
Your help will be much appreciated (I have checked some other SO threads and medium articles, but couldn't find one that combines these features in one place with and preferably with optimized design for scalability/price using Firestore and Flutter).
I think that You can do this:
Widget build(ctx) {
return ListView.builder(
itemCount: snapshot.data.size,
itemBuilder: (index, ctx) =>_catche[index],
)
}
and for _catche:
List<Widget> _catche = [/*...*/];
// initialize on load
I would like to know how can I get access to the fields of a collection that is inside the start collection? (see image below)
This is the streamBuilder I use to get access to the start(first) collection (posts) but I want a way to transform this streamBuilder so that I can get access to another collection inside the posts location. Thank you
StreamBuilder(
///IF YOU WANT TO CHANGE THE COLECCTION LIST THIS IS THE PLACE TO DO IT
stream: Firestore.instance.collection('posts').snapshots(),
builder: (context, snapshot) {
///THIS IS THE PLACE WHEN YOU CAN ADD AN ANIMATION
if (!snapshot.hasData) return const Text('Loading...');
return ListView.builder(
itemExtent: 100.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
Post post = Post.fromDoc(snapshot.data.documents[index]);
return _buildUserTile(post);
},
);
},[![enter image description here][1]][1]
),
I want to be able to get the data that is inside a colection inside the first colection (posts).
See below my firebase database
I am not sure but maybe you can get an idea from the below link:
https://groups.google.com/forum/#!topic/flutter-dev/ayIxrLiz1eQ
I am building a password manager and I'm trying to save on Firestore reads by displaying data in Map. The idea is to have a document (for each password category) and have the passwords stored as maps in it. See example screenshots here:
The idea is that users click on each password (map) and the app takes them to the relevant one using indexes. I then want the data from each map to be sorted separately so that they can live in their own Text widgets. But I haven't seen any possibility of displaying map data in Flutter yet.
I've tried some of the examples from here but haven't been able to display the data from the map - https://github.com/fireship-io/flutter-base/blob/master/lib/main.dart
Any suggestions would be much appreciated.
new StreamBuilder(
stream: Firestore.instance
.collection('users')
.document(userDocSTRING.toString())
.collection(userPassSTRING.toString())
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// If no data is present, display a waiting indicator to the user
// If Null, red screen displays
return Center(child: CircularProgressIndicator());
} else {
// Debug print for Ryan
// print(snapshot.data[0].data.toString());
return new ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot =
snapshot.data.documents[index];
return ListTile(
leading: Container(
child: IconButton(
icon: Icon(Icons.content_copy),
color: lightCardCOLOR,
title: Text(documentSnapshot['Name']
As you can see from the code above, fetching fields from documents is easy enough but I don't want each password to have it's own document. I want a document to hold multiple Maps which corresponds to a password. So documentSnapshot['Name'] I want to be the name or value of a map
I'll suggest that your attempt to "save on Firestore reads" is making it more difficult for you to model and display the data. It also won't scale, since the maximum size of a document is 1MB. Consider storing each password in a different document to make this easier. Document reads are not really very expensive, and the Firebase SDK will cache them locally to avoid the cost of reads when queried.