inject static method

dynamic inject(
  1. dynamic instance,
  2. Map<String, dynamic> values, {
  3. dynamic coerce(
    1. dynamic value,
    2. ClassMirror targetClass
    )?,
  4. void onCoerceError(
    1. dynamic o,
    2. String field,
    3. dynamic value,
    4. ClassMirror targetClass,
    5. dynamic error,
    )?,
  5. void onSetterError(
    1. dynamic o,
    2. String field,
    3. dynamic value,
    4. dynamic error,
    )?,
  6. void validate(
    1. dynamic o,
    2. String field,
    3. dynamic value
    )?,
  7. bool silent = false,
})

Injects the given values into the given object. *

  • For example,
  • ObjectUtil.inject(instance, {"user.name": userName, "foo": whatever});
    
    • instance - the object to inject the value.
    • values - the map of values. The key is the field name, such as name,
  • field1.field2 and so on.
    • coerce - used to coerce the given object to the given type.
  • If omitted or null is returned, the default coercion will be done (
  • it handles the basic types: int, double, String, num, and Datetime).
    • onCoerceError - used to handle the coercion error.
  • If not specified, the exception won't be caught.
    • onSetterError - used to handle the error thrown by a setter.
  • If not specified, the exception won't be caught. ** validate - used to validate if the coerced value can be assigned.
    • silent - whether to ignore if no field matches the keys of the given
  • values.
  • If false (default), an exception will be thrown.
    • Returns instance

Implementation

static inject(instance, Map<String, dynamic> values,
    {coerce(value, ClassMirror targetClass)?,
    void onCoerceError(o, String field, value, ClassMirror targetClass, error)?,
    void onSetterError(o, String field, value, error)?,
    void validate(o, String field, value)?,
    bool silent = false}) {
  l_keys:
  for (var key in values.keys) {
    final fields = key.split('.');
    final value = values[key];
    var o2 = instance;
    for (int i = 0, until = fields.length - 1; i < until; ++i) {
      final field = fields[i].trim();

      //nothing to do if silent && no getter matches the first element of fields
      if (silent && ClassUtil.getGetterType(reflect(o2).type, field) == null)
        continue l_keys;

      var o3 = reflect(o2).getField(Symbol(field)).reflectee;
      if (o3 == null) {
        if (silent && ClassUtil.getSetterType(reflect(o2).type, field) == null)
          continue l_keys;

        if (onSetterError != null) {
          try {
            o3 = _autoCreate(o2, field);
          } catch (err) {
            onSetterError(o2, field, o3, err);
            continue l_keys;
          }
        } else {
          o3 = _autoCreate(o2, field);
        }
      }
      o2 = o3;
    }

    _inject(o2, fields.last.trim(), value,
      coerce, onCoerceError, onSetterError, validate, silent);
  }
  return instance;
}