extractPath<R> method

R? extractPath<R>(
  1. String path
)

从 Map 中提取嵌套字段(支持路径,如 'user.name') 适用于从 Map<String, dynamic> 中提取嵌套字段值

如果数据不是 Map 类型或路径不存在,自动返回 null 内部已处理类型转换和异常,用户只需要提供路径

示例:

final userName = response.extractPath<String>('user.name');
final userId = response.extractPath<int>('user.profile.id');

Implementation

R? extractPath<R>(String path) {
  return extract<R>((data) {
    if (data is! Map<String, dynamic>) return null;
    final keys = path.split('.');
    dynamic value = data;
    for (final key in keys) {
      if (value is Map<String, dynamic>) {
        value = value[key];
      } else {
        return null;
      }
    }
    if (value is R) return value;
    if (value == null) return null;
    try {
      return value as R;
    } catch (e) {
      return null;
    }
  });
}