Reputation: 11
Slowly getting to grips with Flutter and Dart as my new hobby. Any advice or help you can give is always appreciated! I am trying to implement a simple friend system, where you can search for another user and add them as a friend.
To achieve this, I want to use .where('friends', arrayContains: 'user.uid') in stream of StreamBuilder, to only show those user cards in the list on the screen.
class friendsList extends StatelessWidget {
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return
StreamBuilder(
stream: Firestore.instance
.collection('users')
.where('friends', arrayContains: user.uid).snapshots(),
builder: (context, documents) {
if (documents.hasData) {
return
Container(
height: 180,
child:
ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 1,
itemBuilder: (context, index) {
DocumentSnapshot friends = documents.data.documents[index];
However, when I go to run my app, it shows error:
`The following RangeError was thrown building:
RangeError (index): Invalid value: Valid value range is empty: 0
When the exception was thrown, this was the stack
List.[](dart:core-patch/growable_array.dart:149:60)
friendsList.build.<anonymous closure>.<anonymous closure>
Does anyone know what I can do about this error and retrieve the documents that have the friends array with the logged in user UID?
Again any advice and help is appreciated. Screenshot of Cloud Firestore is here
Upvotes: 0
Views: 1246
Reputation: 1
It could be the case that you are printing the results of an empty data from firebase.
Stream<List<Model>> fetchStream({@required String userUID}) {
return nestsCollection
.where("participants", arrayContains: userUID)
.snapshots()
.map((snapshot) {
// print(snapshot.docs[0].data()['nestName']);
return snapshot.docs
.map((document) => Model.fromFirestore(document))
.toList();
});
}
Upvotes: 0
Reputation: 11
I left my project for two days and rebuilt the app in the last hour. To my surprise, '.where('friends', arrayContains: user.uid)' now works!
When the app starts, I now have a ListView of all users who are a friend of the currently logged in user.
On the profile page of each user is a Floating Action Button that when pressed, add's the currently logged in user's UID to a 'friends' array in the document of that friend.
With StreamBuilder and ListView, when the logged in user then goes to their friends page, they see every user that has the logged in user's UID in their 'friends' array
Upvotes: 1