firstWhere<T extends Model> static method

Future<T?> firstWhere<T extends Model>({
  1. required String field,
  2. String comp = "==",
  3. required dynamic value,
})

Returns first record matching where() condition.

Implementation

static Future<T?> firstWhere<T extends Model>({required String field, String comp = "==", required dynamic value}) async {
  final constructor = _jsonConstructors[T];
  if (constructor == null) return null;

  const allowedOps = ['=', '==', '!=', '<', '>', '<=', '>=', 'LIKE'];
  if (!allowedOps.contains(comp.toUpperCase()) && comp != "==") {
    if (comp == "==") {
      comp = "=";
    } else {
      throw ArgumentError("Invalid SQL operator: $comp");
    }
  } else if (comp == "==") {
    comp = "=";
  }

  try {
    final maps = await _database.query(_getTableName<T>(), where: '$field $comp ?', whereArgs: [value], limit: 1);

    if (maps.isNotEmpty) {
      return constructor(maps.first) as T;
    }
    return null;
  } catch (e) {
    return null;
  }
}