I am new to dart, and I came across the following code. This apparently updates the document in the firebase. Can someone explain in detail, what it really does?
abstract class FirestoreDocumentUpdater {
static Future<void> update(
// ignore: use_function_type_syntax_for_parameters
DocumentReference<Map<String, dynamic>> documentRef,
Map<String, dynamic> map) {
debugPrint('update function called');
return documentRef.update(
Map.fromEntries(
map.entries.map(
(e) {
return MapEntry(
e.key,
switch (e.value) {
DateTime t => toJsonDateTime(t),
Duration d => toJsonDuration(d),
Enum t => t.name,
_ => e.value,
});
},
),
),
);
}
}
Timestamp? toJsonDateTime(DateTime? dateTime) {
if (dateTime == null) return null;
return Timestamp.fromDate(dateTime);
}
int toJsonDuration(Duration duration) {
return duration.inMicroseconds;
}
2
Answers
A
MapEntry
is simply the elements of aMap
. Consider this map:This is a map with map entries
MapEntry('key','value')
andMapEntry('foo','bar')
;Now what that code does is simply change the values of a
Map
so that certain values are converted to another value. It turns this map:into
The code is slightly more confusing than it needs to be due to a poor name choice. For this reason I am replacing the parameter
map
withinputMap
.