Flutter Hive getter 没有为“hiveobjectmixin”类型定义
Posted
技术标签:
【中文标题】Flutter Hive getter 没有为“hiveobjectmixin”类型定义【英文标题】:Flutter Hive getter isn't defined for the type 'hiveobjectmixin' 【发布时间】:2021-10-19 11:32:24 【问题描述】:在创建模型以在 2 个模型之间建立关系后,我无法从嵌套关系中获取字段数据
我有一个用户模型,其中包含其他模型作为事务,即HiveList
,现在当我尝试使用以下代码从事务中获取cost
等字段时:
final Box<User> _user = Hive.box<User>('user');
print('$_user.values.first.transactions.first.cost');
我得到这个错误:
错误:没有为类型“HiveObjectMixin”定义吸气剂“成本”。 ([xxxx] 处的 undefined_getter lib/src/screens/dashboard/tabs/screen_transactions.dart:85)
型号:
@HiveType(typeId: 1)
class User extends HiveObject
@HiveField(0)
late String nameFamily;
@HiveField(1)
late String apiToken;
@HiveField(2)
late String mobileNumber;
@HiveField(3)
late HiveList transactions;
@HiveType (typeId: 4)
class Transactions extends HiveObject
@HiveField(0)
late int cost;
@HiveField(1)
late int type;
@HiveField(2)
late String dateTime;
适配器:
class UserAdapter extends TypeAdapter<User>
@override
final int typeId = 1;
@override
User read(BinaryReader reader)
final numOfFields = reader.readByte();
final fields = <int, dynamic>
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
;
return User()
..nameFamily = fields[0] as String
..apiToken = fields[1] as String
..mobileNumber = fields[2] as String
..transactions = (fields[5] as HiveList).castHiveList();
@override
void write(BinaryWriter writer, User obj)
writer
..writeByte(6)
..writeByte(0)
..write(obj.nameFamily)
..writeByte(1)
..write(obj.apiToken)
..writeByte(2)
..write(obj.mobileNumber)
..writeByte(3)
..write(obj.transactions);
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is UserAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
class WalletAdapter extends TypeAdapter<Wallet>
@override
final int typeId = 3;
@override
Wallet read(BinaryReader reader)
final numOfFields = reader.readByte();
final fields = <int, dynamic>
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
;
return Wallet()..total = fields[0] as int;
@override
void write(BinaryWriter writer, Wallet obj)
writer
..writeByte(1)
..writeByte(0)
..write(obj.total);
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is WalletAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
【问题讨论】:
【参考方案1】:我通过cast()
方法解决了这个问题,我应该将哪个类用作List
,例如:
_user.values.first.transactions.cast().cost
【讨论】:
以上是关于Flutter Hive getter 没有为“hiveobjectmixin”类型定义的主要内容,如果未能解决你的问题,请参考以下文章
Flutter:没有为“Box”类型定义方法“listenable”(使用 Hive)
Flutter/Firebase - List<dynamic> 没有实例 getter 'documents'
Flutter Firestore QuerySnapshot 没有 getter 'document 的实例
Flutter - 为 API 实现 JSON getter