I want to check if a field exists in a document in firebase firestore or not.
Asked
Active
Viewed 895 times
4 Answers
1
To check if a field exists in a document, simply use this code:
Future updateUserFields() async {
var userDoc = await FirebaseFirestore.instance.collection("uniaps_users").doc(uid).get();
if (userDoc.exists) {
Map<String, dynamic>? map = userDoc.data() as Map<String, dynamic>?;
if (map!.containsKey('rooms')) {
print("contains it");
} else {
print("does not contain it");
}
}
}
The output will be: does not contain it
because in the document: FN1YRrruF2QQuYN0YV4492CpCge2
doesn't contain the rooms
field.
The trick is to cast the userDoc.data() to be a map, so that you can be able to use the method containsKey('put the field here')

Dingaan Letjane
- 35
- 6
0
FirebaseFirestore.instance.collection('Products').doc(barcode).get().then((value) {
if (value.data() !=null) {
if (value.data().length>0) {
/// Here I am checking if the field Trigram exist <==///
if (value.data()['Trigram']!=null) {
searchTrigram=value.data()['Trigram'];
} else {
searchTrigram='';
}
}
}
});

Adrian Mole
- 49,934
- 160
- 51
- 83
0
Try this follow demo:
await fireStore
.collection(AppConfig.instance.cUser)
.doc(event.userId)
.get()
.then(
(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
var data = documentSnapshot.data();
var res = data as Map<String, dynamic>;
} else {
//do something
}
},
);
And if you use in StreamBuilder:
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection(AppConfig.instance.cUser)
.doc(AppConfig.instance.cListChat)
.collection(widget.userId)
.orderBy('create_at', descending: true)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> chatSnapshot) {
if (chatSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Container(),
);
}
return ListView(
reverse: true,
controller: _controller,
physics: const BouncingScrollPhysics(),
children:
chatSnapshot.data!.docs.map((DocumentSnapshot document) {
if(document.exists){
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
var _chat = ChatData.fromJson(data);
return Container();
} else {
return Container();
}
}).toList(),
);
},
),

Xuuan Thuc
- 2,340
- 1
- 5
- 22
0
I had a case with user and user's info:
First, I got user's data from Firebase:
Future<DocumentSnapshot> _getUserData() async {
final user = FirebaseAuth.instance.currentUser;
QuerySnapshot querySnapshot = await _db
.collection('users')
.where('email', isEqualTo: user!.email.toString())
.get();
DocumentSnapshot userDoc = querySnapshot.docs.first;
return userDoc;
}
Saved it in variable
AsyncSnapshot<DocumentSnapshot<Object?>> user = snapshot;
And latere when I wanted to check if description field in user object exists:
String description = user.data!.data().containsKey('description')
? user.data!.get('description')
: "-";