query method
Executes an SQL Query that return a single value params - an optional list of parameters to pass to the query fromMap - a function that convert the result map to the returned object singleResult - return an object instead of a list of objects
Implementation
Future<dynamic> query(String sql,
{List<Object?> params = const [],
FromMap? fromMap,
bool singleResult = false,
String? dbName}) async {
late List<Map> results;
if (isWeb()) {
results = await _getDB(dbName).rawQuery(sql, params);
} else {
assert(_getDB(dbName) != null);
results = _getDB(dbName).select(sql, params);
}
//final List<dynamic> results = await _getDB(dbName).rawQuery(sql, params);
if (singleResult) {
if (results.isEmpty) {
return null;
}
// Single results
final Map<String, dynamic> result = results.first as Map<String, dynamic>;
// If only a column has been extracted return the simple object
if (result.keys.length == 1) {
return result[result.keys.first];
}
if (fromMap != null) {
// The fromMap method converts the Map to the returned object
try {
final map = result;
// _rowToMap(result);
return fromMap(map);
} catch (error) {
// ignore: avoid_print
print(error.toString());
}
}
return result;
}
// Multiple results
// Return just a simple field object
if (results.isNotEmpty && results.first.keys.length == 1) {
final String onlyField = results.first.keys.first;
return results.map((e) => e[onlyField]).toList();
}
if (fromMap != null) {
return results
.map((map) => fromMap(map as Map<String, dynamic>))
.toList();
}
// Return a list of Map
return results;
}