extractValue<T> static method
dynamic
extractValue<
T>(
)
Implementation
static extractValue<T>(String reference, Map dataMap) {
dynamic defaultValue = _getDefaultValue<T>(reference);
dynamic value = dataMap[reference];
if (value is String) {
String valueCasted = value;
switch (T) {
case DateTime:
try {
if (RegExp(r'\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} \w+')
.hasMatch(valueCasted)) {
return DateFormat(_dateFormatTimezone).parse(valueCasted, true);
}
if (RegExp(r'\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}(\.\d{1,3})?')
.hasMatch(valueCasted)) {
return AwesomeDateUtils.parseStringToDate(valueCasted);
}
return null;
} catch (err) {
return defaultValue;
}
case String:
return valueCasted;
case Color:
case int:
// Color hexadecimal representation
final RegExpMatch? match =
RegExp(r'^(0x|#)(\w{2})?(\w{6})$').firstMatch(valueCasted);
if (match != null) {
String hex = (match.group(2) ?? 'FF') + match.group(3)!;
final int colorValue = int.parse(hex, radix: 16);
return (T == Color) ? Color(colorValue) : colorValue;
} else if (T == int) {
int? parsedValue = int.tryParse(valueCasted.replaceFirstMapped(
RegExp(r'^(\d+)\.\d+$'), (match) => '${match.group(1)}'));
var finalValue = parsedValue ?? defaultValue;
return finalValue;
}
break;
case double:
double? parsedValue = double.tryParse(valueCasted);
return parsedValue ?? defaultValue;
case bool:
switch (valueCasted.toLowerCase()) {
case 'true':
return true;
case 'false':
return false;
case '1':
return true;
case '0':
return false;
}
return null;
}
}
switch (T) {
case int:
if (value is int) return value;
if (value is double) return value.round();
return defaultValue;
case double:
if (value is int) return value.toDouble();
if (value is double) return value;
return defaultValue;
case Color:
switch (value.runtimeType) {
case int:
return Color(value);
case MaterialColor:
value = (value as MaterialColor).shade500;
break;
case MaterialAccentColor:
value = Color((value as MaterialAccentColor).value);
break;
case CupertinoDynamicColor:
value = Color((value as CupertinoDynamicColor).value);
break;
}
break;
case Duration:
if (value == null) return defaultValue;
Duration? duration;
if (value is String) duration = Duration(seconds: int.parse(value));
if (value is int) duration = Duration(seconds: value);
return (duration?.inSeconds ?? -1) < 0 ? defaultValue : duration;
case bool:
if (value == null) return defaultValue;
if (value is int) return value == 1;
if (value is bool) return value;
return defaultValue;
}
if (value is T) return value;
return defaultValue;
}