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.
The intended outcome is:
- Logged in user goes to profile of friend and clicks 'add friend' button.
- Firestore has a users collection. In that collection is a document for each user with profile information, including an array 'friends'. Clicking the 'add friend' button will add the logged in users UID to that second person's 'friends' array.
- Then on a Friends screen, I am using a StreamBuilder and Listview.builder to show all users as cards, that have the logged in user's UID in their 'friends' array.
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.
Here is the code I have written:
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>
Notes:
- itemCount is hardcoded to 1 right now. I am only expecting 1 user to be returned while I am testing. I will populate Firestore with more users once it is all working.
- When I swap arrayContains for something simpler like .where('displayName', isEqualTo: 'My Name').snapshots(), , the app works without errors
- user.uid has been tested and does contain the intended string
- Arrays are present with values in Firestore (See link at bottom of post)
- I have setup an index for the values I am using in 'users'
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