You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中用Drift(原Moor)高效获取对象属性的去重值

在Drift中高效获取去重分类列表的方法

直接利用Drift的DSL或原生SQL让数据库完成去重和列提取操作,完全不需要先查询全量Item再在客户端处理,效率会大幅提升,解决你提到的两个问题:

方法一:使用Drift类型安全DSL

在你的Dao类中添加以下方法:

import 'package:drift/drift.dart';

// 假设你的items表定义
class Items extends Table {
  TextColumn get category => text()();
  // 其他列定义...
}

@DriftAccessor(tables: [Items])
class ItemDao extends DatabaseAccessor<MyDatabase> with _$ItemDaoMixin {
  ItemDao(MyDatabase db) : super(db);

  Future<List<String>> getDistinctCategories() {
    return select(items)
        .addColumns([items.category]) // 仅查询category列,避免返回整个Item对象
        .distinct() // 启用SQL的DISTINCT关键字,数据库层面去重
        .map((row) => row.read(items.category)!) // 提取category字符串
        .get();
  }
}

方法二:使用原生SQL查询

如果你更习惯原生SQL写法,也可以这样实现:

Future<List<String>> getDistinctCategories() {
  return customSelect(
    'SELECT DISTINCT category FROM items',
    readsFrom: {items}, // 告知Drift查询依赖的表,支持自动迁移等特性
  ).map((row) => row.read<String>('category')).get();
}

关键优势

  • 只请求category列,减少磁盘IO开销
  • 由数据库引擎执行去重,效率远高于客户端遍历转Set,数据量越大优势越明显

内容的提问来源于stack exchange,提问作者Ivan C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:50:20