flutterdartobjectboxflutter-objectbox

How to conditionally add a condition to my objectbox query?


I have this method to find all my Clientes:

static Future<List<Cliente>> findAll({
  int limit = 50,
  String? cnpjCpf,
  String? fantasia,
}) async {
  List<Cliente> clientes = [];

  final boxCliente = objectBox.store.box<Cliente>();

  Query<Cliente> query = boxCliente
      .query(Cliente_.cnpjCpf
          .contains(cnpjCpf ?? "")
          .or(Cliente_.fantasia.contains(fantasia ?? "")))
      .order(Cliente_.fantasia)
      .build();

  query.limit = limit;

  clientes = await query.findAsync();

  return clientes;
}

Now, instead of adding all conditions like the sample above, I need to conditionally add my conditions, i.e, if cnpjCpj != null then add it to the QueryBuilder.

I was thinking, maybe something like this:

static Future<List<Cliente>> findAll({
  int limit = 50,
  String? cnpjCpf,
  String? fantasia,
}) async {
  List<Cliente> clientes = [];

  final boxCliente = objectBox.store.box<Cliente>();

  final queryBuilder = boxCliente.query();

  if (cnpjCpf != null && cnpjCpf.isNotEmpty) {
    queryBuilder.equal(Cliente_.cnpjCpf, cnpjCpf);
  }

  if (fantasia != null && fantasia.isNotEmpty) {
    queryBuilder.contains(Cliente_.fantasia, fantasia);
  }

  queryBuilder.order(Cliente_.fantasia);

  Query<Cliente> query = queryBuilder.build();

  query.limit = limit;

  clientes = await query.findAsync();

  return clientes;
}

Any one knows how to do this? there is no equals or contains to the QueryBuilder object.


Solution

  • First combine the conditions, then once done pass them to the .query(conditions) method. So something like:

    var Condition<Cliente>? conditions = null;
    
    if (cnpjCpf != null && cnpjCpf.isNotEmpty) {
      conditions = Cliente_.cnpjCpf.equal(cnpjCpf);
    }
    
    if (fantasia != null && fantasia.isNotEmpty) {
      if (conditions == null) {
        conditions = Cliente_.fantasia.equal(fantasia);
      } else {
        conditions = conditions.or(Cliente_.fantasia.equal(fantasia));
      }
    }
    
    if (conditions != null) {
      final query = boxCliente.query(conditions).build();
    }