readValue static method

dynamic readValue(
  1. dynamic data,
  2. String? tag
)

Implementation

static dynamic readValue(dynamic data, String? tag)
{
  if (data == null || (data is List && data.isEmpty) || tag == null) return null;

  // Get Dot Notation
  DotNotation? dotNotation = DotNotation.fromString(tag);

  if (data is List<dynamic>) data = data.isNotEmpty ? data[0] : null;

  if (dotNotation != null){
    for (NotationSegment? property in dotNotation) {
      if (property != null)
      {
        if (data is Map)
        {
          // attributes are named with an underscore
          // to make it easier for the user, we first look for the
          // property by name, then if not found, look for it by _name
          var name  = property.name;
          var myName = "_$name";
          if (!data.containsKey(name) && (!data.containsKey(myName)))
          {
            data = null;
            break;
          }
          data = data.containsKey(name) ? data[name] : data[myName];

          if ((data is Map)  && (property.offset > 0)) data = null;
          if ((data is List) && (property.offset > data.length)) data = null;
          if ((data is List) && (property.offset < data.length) && (property.offset >= 0))  data = data[property.offset];
        }

        else if (data is List)
        {
          if (data.length < property.offset)
          {
            data = null;
            break;
          }
          data = data[property.offset];
          if ((data is Map) && (data.containsKey(property.name))) data = data[property.name];
        }

        else
        {
          data = null;
          break;
        }
      }
    }}

  // this is a very odd case. if the element contains attributes, the element value will be put into a
  // map field called "value" and its attributes will be mapped to underscore (_) names _attributename
  if ((data is Map) && (data.containsKey('value'))) data = data['value'];

  // return result;
  return data;
}