Issue
I am retrieving a list of users with a Stream and I need to ignore the current user. I did this once with a Future List, but with StreamBuilder an error appears when defining the list of documents.
So here's what's working (Future):
Future<List<Users>> _getUsers() async {
Firestore db = Firestore.instance;
QuerySnapshot querySnapshot = await db
.collection('users')
.getDocuments();
List<Users> usersList = [];
for (DocumentSnapshot item in querySnapshot.documents) {
var data = item.data;
if (data["id"] == _userId) continue;
Users user = Users();
user.name = data["name"];
user.username = data["username"];
user.id = data["id"];
usersList.add(user);
}
return usersList;
}
And this is not working (Stream):
startConnecting() {
return Expanded(
child: StreamBuilder(
stream:Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text(
"Nothing."
),
),
);
}
return ListView.builder(
padding: EdgeInsets.only(top: 10),
scrollDirection: Axis.vertical,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildListUsers(context, snapshot.data.documents[index]),
);
},
),
);
}
Widget _buildListUsers(BuildContext context, DocumentSnapshot document) {
List<Users> usersList = [];
for (DocumentSnapshot item in document) {
In that last 'document' an error message appears: "The type 'DocumentSnapshot' used in the 'for' loop must implement Iterable."
var data = item.data;
if (data["id"] == _userId) continue;
Users user = Users();
user.name = document["name"];
user.username = document["username"];
user.id = document["id"];
usersList.add(user);
return ListTile(
...
);
}
}
I looked for this error but did not find anything like it. It must be something simple that I'm missing.
Solution
You don't have to loop through a DocumentSnapshot, because as stated, it's not an iterable object, it's a single document. So change this:
Widget _buildListUsers(BuildContext context, DocumentSnapshot document) {
List<Users> usersList = [];
for (DocumentSnapshot item in document) {
To this:
Widget _buildListUsers(BuildContext context, DocumentSnapshot document) {
List<Users> usersList = [];
//for (DocumentSnapshot item in document) { ==> comment out this for loop
var data = document.data;
//keep your logic here as it
//remove the closing curly brace at the end, because there is no more for loop.
To answer your second question in the comment, do this:
if (data["id"] != _userId) {
Users user = Users();
user.name = data["name"];
user.username = data["username"];
user.id = data["id"];
usersList.add(user);
}
Answered By - Huthaifa Muayyad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.