getSingleOrNull method

  1. @override
Future<T?> getSingleOrNull()
override

Executes this statement, like Selectable.get, but only returns one value. If the result too many values, this method will throw. If no row is returned, null will be returned instead.

Be aware that this operation won't put a limit clause on this statement, if that's needed you would have to do use SimpleSelectStatement.limit:

Future<TodoEntry> loadMostImportant() {
  return (select(todos)
   ..orderBy([(t) =>
      OrderingTerm(expression: t.priority, mode: OrderingMode.desc)])
   ..limit(1)
  ).getSingle();
}

You should only use this method if you know the query won't have more than one row, for instance because you used limit(1) or you know the where clause will only allow one row.

See also: Selectable.getSingle, which can be used if the query will always evaluate to exactly one row.

Implementation

@override
Future<T?> getSingleOrNull() async {
  final list = await get();
  final iterator = list.iterator;

  if (!iterator.moveNext()) {
    return null;
  }
  final element = iterator.current;
  if (iterator.moveNext()) {
    throw StateError('Expected exactly one result, but found more than one!');
  }

  return element;
}