get method

dynamic get(
  1. Object field
)

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 field "$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 "$key" 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 "$value" does not exist within the $DocumentSnapshotPlatform',
      );
    }
  }

  return _findComponent(0, snapshotData);
}