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

Flutter Isar数据库如何检查Schema是否为空?

在Isar数据库中检查Schema集合是否为空的方法

Isar没有提供和ObjectBox的box.isEmpty()完全对应的直接方法,但可以通过两种简单方式判断指定Schema的集合是否为空,满足你"仅当数据库为空时插入数据"的需求:

方法1:通过count()判断

调用对应Schema集合的count()方法,若返回值为0则说明集合为空:

final isar = await Isar.open([YourTargetSchema]);
final isCollectionEmpty = await isar.yourTargetSchema.count() == 0;

if (isCollectionEmpty) {
  // 执行初始化数据插入
  await isar.writeTxn(() async {
    await isar.yourTargetSchema.putAll([/* 待插入的数据列表 */]);
  });
}

方法2:通过findFirst()判断

调用findFirst()方法,若返回null则表示集合中没有任何数据:

final isar = await Isar.open([YourTargetSchema]);
final firstItem = await isar.yourTargetSchema.findFirst();
final isCollectionEmpty = firstItem == null;

if (isCollectionEmpty) {
  // 执行单条或多条数据插入
  await isar.writeTxn(() async {
    await isar.yourTargetSchema.put(YourTargetSchemaObject(/* 数据字段赋值 */));
  });
}

注意点

  • 插入数据必须在**写事务(writeTxn)**中执行,保证数据操作的原子性和一致性。
  • 若应用包含多个Schema,需要分别对每个Schema对应的集合进行空判断。

内容的提问来源于stack exchange,提问作者Waruna Kaushalya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:40:28