Show this text when a document field is empty
399
you are checking here if the document field is null or not but you need to check whether the field is empty string("") or not since thats how picture shows.
change this line
if (snapshot.data?.data()?.containsValue('groupId') == null)
containsValue is checking if the object from firebase which is something like key and value pair, contains the given [value], in this case 'groupId'. but groupId is key not value from picture shown in your case
try this
String userUid = FirebaseAuth.instance.currentUser!.uid;
bool checkEmpty = false;
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: firestore
.collection('users')
.doc("userUid")
.snapshots(),
builder: (context, snapshot) {
snapshot.data!.data()?.forEach((key, value) {
if (key == 'groupId') {
checkEmpty = value == '';
}
});
return checkEmpty?
const Text('no data'):
const Text('has data')
Author by
It'sPhil
Updated on January 05, 2023Comments
-
It'sPhil 10 months
I am having trouble in the documentSnapshot. I want to show "No data" when the document field is empty. And show "has data" when the document field has something inside. The problem is that either when the document field has something inside or not it’s always showing "no data"
class _TestState extends State<Test> { String userUid = FirebaseAuth.instance.currentUser!.uid; @override Widget build(BuildContext context) { return StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>( stream: FirebaseFirestore.instance .collection("users") .doc(userUid) .snapshots(), builder: (context, snapshot) { if (snapshot.data?.data()?.containsValue('groupId') ==null) { return const Text("no data"); } else { //It’s always show this return const Text('has data'); } }); } }
-
user18309290 over 1 yearThere is probably an error in the stream.
-
It'sPhil over 1 yearWhat do you mean?. Because in my code there’s no error or anything.
-
user18309290 over 1 yearCheck if a document exists: pub.dev/documentation/cloud_firestore/latest/cloud_firestore/….
-
It'sPhil over 1 yearThe thing is I don’t want to check If the doc exist. I want to check If the doc field is empty or not.
-
-
It'sPhil over 1 yearIt’s still the same. It says this
Equality operator '==' invocation with references of unrelated types.
And I tried// ignore: unrelated_type_equality_checks
But nothing change. -
It'sPhil over 1 year_CastError (Null check operator used on a null value)
return checkEmpty! ? const Text('no data') : const Text('has data');
-
brook yonas over 1 yearhave you checked checkEmpty value in the if clause, please share your code
-
It'sPhil over 1 yearI ve share my code above .
-
brook yonas over 1 yearcheck it again, just edited it
-
It'sPhil over 1 yearOmg!! Its work thank you so much . You have no idea how long I ve been working on this problem.
-
brook yonas over 1 yearyes, no problem my friend dart.dev/codelabs/null-safety. read about null safety here.