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

Flutter中Hive存储自定义对象列表重启后数据丢失问题求助

问题解决步骤

1. 为LocalDatabase的自定义字段添加@HiveField注解

你的LocalDatabase类中仅lastUpdate字段添加了@HiveField注解,其余自定义对象/列表字段未标记——Hive的序列化适配器只会处理带有该注解的字段,这是重启后数据丢失的核心原因。修改后的代码如下:

part 'hive_storage.g.dart';

@HiveType(typeId: 0)
class LocalDatabase extends HiveObject {
  @HiveField(0)
  DateTime? lastUpdate;
  
  @HiveField(1) // 为列表字段添加注解,分配唯一ID
  List<Schulaufgaben>? examDates;
  
  @HiveField(2) // 为列表字段添加注解,分配唯一ID
  List<AllgemeineTermine>? appointments;
  
  @HiveField(3) // 为对象字段添加注解,分配唯一ID
  Schulinformationen? schoolInformation;
}

2. 确认自定义类的Hive配置正确性

确保Schulaufgaben、AllgemeineTermine、Schulinformationen都正确配置了Hive注解,示例如下(以Schulaufgaben为例):

part 'schulaufgaben.g.dart';

@HiveType(typeId: 1) // 分配全局唯一的typeId,不可与其他类重复
class Schulaufgaben extends HiveObject {
  @HiveField(0)
  String? taskTitle;
  
  @HiveField(1)
  DateTime? dueDate;
  
  // 你的fromJson/toJson方法...
}

每个自定义类都需要通过hive_generator生成对应的适配器(如SchulaufgabenAdapter)。

3. 调整适配器注册顺序

Hive需要先注册子对象的适配器,再注册包含它们的父类适配器。修改main函数的初始化逻辑:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  
  // 先注册所有自定义子对象的适配器
  Hive.registerAdapter(SchulaufgabenAdapter());
  Hive.registerAdapter(AllgemeineTermineAdapter());
  Hive.registerAdapter(SchulinformationenAdapter());
  
  // 最后注册LocalDatabase的适配器
  Hive.registerAdapter(LocalDatabaseAdapter());
  
  await Hive.openBox<LocalDatabase>('localDatabase');
  runApp(const MyApp());
}

4. 重新生成Hive适配器

修改注解后,必须重新运行build_runner命令更新适配器代码:

flutter pub run build_runner build --delete-conflicting-outputs

5. 优化数据保存逻辑

如果你的LocalDatabase是单例数据(仅需存储一份),建议用固定key存储而非add(add会生成多条数据),避免后续读取时出现混乱:

final localDbBox = Hive.box<LocalDatabase>('localDatabase');

final databaseObject = LocalDatabase()
  ..lastUpdate = DateTime.now()
  ..examDates = await _db.getExamDates()
  ..appointments = await _db.getAppointments();

// 用固定key存储,覆盖旧数据
await localDbBox.put('saved_data', databaseObject);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:15:16