getPath<T> method

T? getPath<T>(
  1. String path
)

Navigates a dot-separated path into nested Maps and returns the value at the leaf.

If any key along the path is absent or refers to a non-Map value, returns null.

final json = {'a': {'b': {'c': 42}}};
json.getPath<int>('a.b.c');    // 42
json.getPath('a.b.x');         // null
json.getPath('a.x.y');         // null

Implementation

T? getPath<T>(String path) {
  final keys = path.split('.');
  dynamic current = this;
  for (final key in keys) {
    if (current is! Map) return null;
    if (!current.containsKey(key)) return null;
    current = current[key];
  }
  return current is T ? current : null;
}