Created
January 9, 2019 22:36
-
-
Save magillus/48d4328d79cadb03032bd2db40d48571 to your computer and use it in GitHub Desktop.
Dart useful methods for parsing Json/map to object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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