I have a list that contains several documentsnapshots. when I do a list.contains(documentsnapshot) it always returns false. example:
DocumentSnapshot a = document;
List<DocumentSnapshot> snapshots = []
snapshots.add(a);
snapshots.contains(a) // false
stripped down version of actual code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class AddUsersDialog extends StatefulWidget {
@override
_AddUsersDialogState createState() => _AddUsersDialogState();
}
class _AddUsersDialogState extends State<AddUsersDialog> {
List<DocumentSnapshot> selected = [];
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
child: Column(
children: <Widget>[
// row to display the selected users
Row(
children: List.generate(selected.length,
(index) => InkWell(
onTap: () => setState(() => selected.removeAt(index)),
child: Text(selected[index]['name']),
);
),
),
// list of all users
StreamBuilder<QuerySnapshot>(
stream: getUsers(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
List<DocumentSnapshot> users = snapshot.data.documents;
return Flexible(
child: ListView.builder(
itemCount: users.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Text(users[index]['name']),
onTap: () => setState(() {
if (selected.contains(users[index])) return;
selected.add(users[index]);
}),
);
},
),
);
}
}
),
],
),
),
);
}
}
I get the streambuilder data, it displays nicely, I can add documentSnapshots to the selected list, and I can remove them again. only when I check in the users list if the user is already in the selected list, it will always return false, even though when I print the list, and the user, I can see that it's in there.
Solution apparently directly comparing DocumentSnapshots is going to give issues as described in the comments of Morez' answer. I solved it by creating a custom contains function
bool contains(List<DocumentSnapshot> list, DocumentSnapshot item) {
for (DocumentSnapshot i in list) {
if (i.documentID == item.documentID) return true;
}
return false;
}