inject static method
dynamic
inject(
- dynamic instance,
- Map<
String, dynamic> values, { - dynamic coerce(
- dynamic value,
- ClassMirror targetClass
- void onCoerceError(
- dynamic o,
- String field,
- dynamic value,
- ClassMirror targetClass,
- dynamic error,
- void onSetterError(
- dynamic o,
- String field,
- dynamic value,
- dynamic error,
- void validate(
- dynamic o,
- String field,
- dynamic value
- 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 asname
,
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
, andDatetime
). -
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
- Returns
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;
}