Skip to content

Instantly share code, notes, and snippets.

@magillus
Created January 9, 2019 22:36
Show Gist options
  • Save magillus/48d4328d79cadb03032bd2db40d48571 to your computer and use it in GitHub Desktop.
Save magillus/48d4328d79cadb03032bd2db40d48571 to your computer and use it in GitHub Desktop.
Dart useful methods for parsing Json/map to object
bool whenNull(dynamic value) {
return value == null;
}
bool whenNotNull(dynamic value) {
return value != null;
}
bool whenNullMap(String key, value) {
return value == null;
}
bool whenNotNullMap(String key, value) {
return value != null;
}
double parseValue(dynamic value, [double defValue]) {
if (value == null) {
return defValue;
}
try {
if (value is String) {
return double.parse(value);
} else if (value is double) {
return value;
} else if (value is num) {
return value.toDouble();
} else {
return defValue;
}
} catch (ex) {
return defValue;
}
}
dynamic getSafeBool(Map<dynamic, dynamic> map, String key,
{bool defValue = false}) {
var value = getSafe(map, key);
return value == "true" || value == 0;
}
dynamic getSafe(Map<dynamic, dynamic> map, String key,
[dynamic defValue = null]) {
var value = defValue;
if (map != null && map.containsKey(key)) {
value = map[key] ?? defValue;
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment