我有这个方法可以找到我所有的
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;
}
现在,我不需要像上面的示例那样添加所有条件,而是需要有条件地添加我的条件,即,如果
cnpjCpj != null
则将其添加到 QueryBuilder
。
我在想,也许是这样的:
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;
}
有人知道该怎么做吗? QueryBuilder 对象没有 equals 或 contains 。
首先组合条件,然后将它们传递给
.query(conditions)
方法。所以类似:
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();
}