美文网首页
Flutter之本地数据库 2025-04-16 周三

Flutter之本地数据库 2025-04-16 周三

作者: 松哥888 | 来源:发表于2025-04-15 20:47 被阅读0次

简介

  • 在逐渐云化的移动开发领域,本地数据库使用的场景很少,但是毕竟还有。

  • 常见的有SQLite,Hive,Moor,ObjectBox等;不过我们的应用却选择了Isar,看简介比较适合我们的电商应用。

安装

需要4个组件配合使用,其中dev两个可以看做是代码生成器。

isar_version: &isar_version 3.1.0 # define the version to be used

dependencies:
  isar: *isar_version
  isar_flutter_libs: *isar_version # contains Isar Core

dev_dependencies:
  isar_generator: *isar_version
  build_runner: any

使用注解定义数据模型

要存储的数据类型,定义的字段名字。以下是邮件的例子。

part 'email.g.dart';

@collection
class Email {
  Id id = Isar.autoIncrement; // you can also use id = null to auto increment

  @Index(type: IndexType.value)
  String? title;

  List<Recipient>? recipients;

  @enumerated
  Status status = Status.pending;
}

@embedded
class Recipient {
  String? name;

  String? address;
}

enum Status {
  draft,
  pending,
  sent,
}

打开数据库

这里的打开文档目录需要用到插件path_provider

final dir = await getApplicationDocumentsDirectory();
final isar = await Isar.open(
  [EmailSchema],
  directory: dir.path,
);

查询数据库

用一些比较好理解的函数代替了SQL语句,降低了使用难度。

final emails = await isar.emails.filter()
  .titleContains('awesome', caseSensitive: false)
  .sortByStatusDesc()
  .limit(10)
  .findAll();

数据库检查器

  • 运行程序之后,log会提供一个链接,点击之后,可以在Chrome查看整个数据库。这个功能比较特别,对于调试程序非常有帮助。
log中的链接
  • 检查器可以添加各种过滤器,图像化操作比较直观,非常赞。
看结果

CRUD operations

数据库的基本操作,有简洁的函数

final newEmail = Email()..title = 'Amazing new database';

await isar.writeTxn(() {
  await isar.emails.put(newEmail); // insert & update
});

final existingEmail = await isar.emails.get(newEmail.id!); // get

await isar.writeTxn(() {
  await isar.emails.delete(existingEmail.id!); // delete
});

小结

很有特色,特别是数据库检查器很好。记得当年用OC开发iOS程序调SQLite的时候,查看数据库内容是真的麻烦。

相关文章

网友评论

      本文标题:Flutter之本地数据库 2025-04-16 周三

      本文链接:https://www.haomeiwen.com/subject/ylcsbjtx.html