未分类 · 2023年3月7日 0

Flutter Floor 数据库框架遇到的一些坑

内容纲要

自增主键类型必须设置为 int? 可空类型,否则插入会覆盖原来数据并且id永远为0

  @PrimaryKey(autoGenerate: true)
  int? id;

报错:SqliteException(14): bad parameter or other API misuse, bad parameter or other API misuse (code 21) #731

原因:如果创建数据库时只给数据库文件名称不给路径,就不能正确打开存放数据库文件的文件夹,解决方案:使用路径提供器获取路径以存放数据库文件

AppDatabase? _database;

Future<AppDatabase> getDatabase() async => _database ??= await _getDatabase();

Future<AppDatabase> _getDatabase() async {
  final dir = await getApplicationSupportDirectory();
  return $FloorAppDatabase
      .databaseBuilder(join(dir.path, 'app_database.db'))
      .build();
}