72 lines
1.3 KiB
Dart
72 lines
1.3 KiB
Dart
Map<K, dynamic> toMap<K>(dynamic value, {reserveNull = false}) {
|
|
Map<K, dynamic> map = {};
|
|
|
|
if (value == null) return map;
|
|
|
|
if (value is Map) {
|
|
map = Map.from(value);
|
|
}
|
|
|
|
if (value is List) {
|
|
map = Map.from(value.asMap());
|
|
}
|
|
|
|
if (!reserveNull) {
|
|
map.removeWhere((key, value) => value == null);
|
|
}
|
|
|
|
return map;
|
|
}
|
|
|
|
/// convert snapshot value to a list
|
|
List<dynamic> toList(dynamic value, {reserveNull = false}) {
|
|
List<dynamic> list = [];
|
|
|
|
if (value == null) return list;
|
|
|
|
if (value is List) {
|
|
list = List.from(value);
|
|
}
|
|
|
|
if (value is Map) {
|
|
list = Map.from(value).values.toList();
|
|
}
|
|
|
|
if (reserveNull) {
|
|
return list;
|
|
}
|
|
|
|
return list.where((element) => element != null).toList();
|
|
}
|
|
|
|
/// Convert any data into double or null if it can not be parsed
|
|
double? asDouble(dynamic source) {
|
|
if (source == null) {
|
|
return null;
|
|
}
|
|
return double.tryParse(source.toString());
|
|
}
|
|
|
|
/// Convert any data into int or null if it can not be parsed
|
|
int? asInt(dynamic source, {int? radix}) {
|
|
if (source == null) {
|
|
return null;
|
|
}
|
|
return int.tryParse(source.toString(), radix: radix);
|
|
}
|
|
|
|
bool asBool(dynamic source) {
|
|
if (source == null) {
|
|
return false;
|
|
}
|
|
|
|
if (source is num) {
|
|
return source > 0;
|
|
}
|
|
if (source is bool) {
|
|
return source;
|
|
}
|
|
|
|
return false;
|
|
}
|