get method
Gets a nested field by String or FieldPath from the snapshot.
Data can be accessed by providing a dot-notated path or FieldPath which recursively finds the specified data. If no data could be found at the specified path, a StateError will be thrown.
Implementation
dynamic get(Object field) {
assert(
field is String || field is FieldPath,
'Supported [field] types are [String] and [FieldPath]',
);
if (!exists) {
throw StateError(
'cannot get a field on a $DocumentSnapshotPlatform which does not exist',
);
}
dynamic _findKeyValueInMap(String key, Map<String, dynamic> map) {
if (map.containsKey(key)) {
return map[key];
}
throw StateError(
'field does not exist within the $DocumentSnapshotPlatform',
);
}
FieldPath fieldPath;
if (field is String) {
fieldPath = FieldPath.fromString(field);
} else {
fieldPath = field as FieldPath;
}
List<String> components = fieldPath.components;
Map<String, dynamic>? snapshotData = data();
dynamic _findComponent(int componentIndex, Map<String, dynamic>? data) {
bool isLast = componentIndex + 1 == components.length;
dynamic value = _findKeyValueInMap(components[componentIndex], data!);
if (isLast) {
return value;
}
if (value is Map) {
return _findComponent(
componentIndex + 1, Map<String, dynamic>.from(value));
} else {
throw StateError(
'field does not exist within the $DocumentSnapshotPlatform',
);
}
}
return _findComponent(0, snapshotData);
}