Flutter Web中使用hive_ce从CollectionBox获取数据失败
解决Hive CE获取数据时LinkedMap转Product类型错误的问题
按以下步骤逐一排查:
1. 确认集合获取时指定了正确泛型
你获取_prodsCollection时,必须明确指定泛型<Product>,否则Hive会默认返回LinkedMap:
final _prodsCollection = await collection.openBox<Product>('products');
2. 检查适配器的序列化/反序列化逻辑
确保Product适配器的read和write方法字段顺序严格对应,且typeId唯一:
class ProductAdapter extends TypeAdapter<Product> { @override final int typeId = 1; // 确保这个ID未被其他适配器占用 @override Product read(BinaryReader reader) { // 反序列化顺序要和write完全一致 return Product( id: reader.readString(), name: reader.readString(), // 其他字段按存储顺序读取 ); } @override void write(BinaryWriter writer, Product obj) { // 序列化顺序要和read完全一致 writer.writeString(obj.id); writer.writeString(obj.name); // 其他字段按读取顺序写入 } }
3. 验证存储数据的方式
必须直接存储Product实例,不能存Map对象:
// 正确写法 await _prodsCollection.put('prod1', Product(id: '1', name: '商品A')); // 错误写法(会导致读出来是LinkedMap) await _prodsCollection.put('prod1', Product(id: '1', name: '商品A').toJson());
4. 确认BoxCollection初始化时传入了适配器
初始化BoxCollection时,要把Product适配器加入adapters参数,仅单独调用Hive.registerAdapter在Web环境下可能不生效:
final collection = await BoxCollection.open( 'MyDatabase', ['products'], path: './hive_storage', adapters: [ProductAdapter()], // 必须包含Product适配器 );
5. 清理Web缓存重试
Web环境下Hive数据存在浏览器缓存,若之前存过Map格式的旧数据,会导致类型不匹配。清空浏览器缓存或删除Hive存储目录后,重新初始化测试。
内容的提问来源于stack exchange,提问作者Al-Jaabir
相关产品推荐
相关产品推荐

