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

Flutter桌面应用卸载后如何删除Drift(原Moor)本地数据库

解决Flutter桌面端卸载后Drift/SharedPreferences数据残留问题

核心原因

桌面操作系统(Windows/macOS/Linux)不会像移动端那样,在卸载应用时自动清理应用的私有存储目录。Drift的数据库文件和SharedPreferences的配置文件都存在这些未被系统自动清理的路径下。

解决方案

1. 绑定数据目录到系统可清理位置

修改Drift和SharedPreferences的存储路径,将数据放在系统配合卸载流程可清理的目录中:

  • Windows:选择%LOCALAPPDATA%\<你的应用名>或%APPDATA%\<你的应用名>,通过Inno Setup等安装工具配置卸载时删除该目录。
  • macOS:将数据放在~/Library/Application Support/<你的应用名>,配合官方打包工具的卸载逻辑清理。
  • Linux:使用~/.config/<你的应用名>,通过.deb/.rpm等包管理器的卸载脚本配置目录删除。

修改Drift数据库路径示例:

LazyDatabase _openConnection() {
  return LazyDatabase(() async {
    final dbFolder = await getApplicationSupportDirectory();
    final file = File(p.join(dbFolder.path, 'app_database.sqlite'));
    return NativeDatabase(file);
  });
}

修改SharedPreferences存储路径(需依赖shared_preferences_desktop包):

import 'package:shared_preferences_desktop/shared_preferences_desktop.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

Future<void> initCustomSharedPrefs() async {
  final appDir = await getApplicationSupportDirectory();
  final prefsPath = p.join(appDir.path, 'prefs.json');
  SharedPreferencesDesktop.setPath(prefsPath);
  await SharedPreferences.getInstance();
}

2. 通过安装/卸载脚本主动清理

  • Windows:在Inno Setup等安装工具的卸载脚本中,添加删除数据库、SharedPreferences文件的命令。
  • macOS:在.app包的Contents/Resources中添加卸载脚本,或配合第三方卸载工具执行清理。
  • Linux:在.deb/.rpm包的卸载脚本中,添加删除对应存储目录的命令。

3. 优化手动清理逻辑并主动触发

保留你现有的手动清理代码,修复finally块的外键约束错误,并加入SharedPreferences清理:

Future<void> deleteEverything() async {
  await customStatement('PRAGMA foreign_keys = OFF');
  try {
    await transaction(() async {
      for (final table in allTables) {
        await delete(table).go();
      }
    });
    // 同步清理SharedPreferences
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();
  } finally {
    await customStatement('PRAGMA foreign_keys = ON'); // 恢复外键约束
  }
}

在用户退出应用、注销账号时主动调用该方法,提前清理数据减少残留。

4. 提供用户主动清理入口

在应用设置页面添加「清除所有数据」按钮,调用上述deleteEverything方法,让用户可主动触发数据清理。

内容的提问来源于stack exchange,提问作者Jafar Temirov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:31:04