setStringToAttribute method
Helper to parse a string and update the attribute name accordingly.
If the attribute type is recognized (e.g., int, bool), we parse the string.
Otherwise, store the string as-is.
Implementation
@override
bool setStringToAttribute(String name, String string) {
if (_concept == null) {
throw ConceptException('Entity concept is not defined.');
}
Attribute? attribute =
_concept?.attributes.singleWhereCode(name) as Attribute?;
if (attribute == null) {
String msg = '${_concept?.code}.$name is not correct attribute name.';
throw UpdateException(msg);
}
// If literal 'null', we interpret that as no value.
if (string == 'null') {
return setAttribute(name, null);
}
// Attempt to parse based on declared attribute type.
if (attribute.type?.code == 'DateTime') {
try {
return setAttribute(name, DateTime.parse(string));
} on ArgumentError catch (e) {
throw TypeException('${_concept?.code}.${attribute.code} '
'attribute value is not DateTime: $e');
}
} else if (attribute.type?.code == 'bool') {
if (string == 'true') {
return setAttribute(name, true);
} else if (string == 'false') {
return setAttribute(name, false);
} else {
throw TypeException('${attribute.code} attribute value is not bool.');
}
} else if (attribute.type?.code == 'int') {
try {
return setAttribute(name, int.parse(string));
} on FormatException catch (e) {
throw TypeException('${attribute.code} '
'attribute value is not int: $e');
}
} else if (attribute.type?.code == 'double') {
try {
return setAttribute(name, double.parse(string));
} on FormatException catch (e) {
throw TypeException('${attribute.code} '
'attribute value is not double: $e');
}
} else if (attribute.type?.code == 'num') {
try {
return setAttribute(name, int.parse(string));
} on FormatException catch (e1) {
try {
return setAttribute(name, double.parse(string));
} on FormatException catch (e2) {
throw TypeException(
'${attribute.code} attribute value is not num: $e1; $e2');
}
}
} else if (attribute.type?.code == 'Uri') {
try {
return setAttribute(name, Uri.parse(string));
} on ArgumentError catch (e) {
throw TypeException('${attribute.code} attribute value is not Uri: $e');
}
} else {
// For any other or custom type, store string as-is.
return setAttribute(name, string);
}
}