我正在使用 Flutter 和 Hive 创建一个应用程序,但我还不熟悉它。
我需要在其中有一个初始帐户,因此我为此制作了一个 Hive 框,并且我正在尝试在该框中保存一个帐户对象。
我检查添加打印件,并将对象正确保存在框中。但是当我重新启动应用程序时,打印不再返回值。对象仍然存在,但只有字符串名称字段有值,其他两个为空。
为什么重启后有些字段为空?
第一次运行后的输出
I/flutter (14014): wallet
I/flutter (14014): Currencies.USD
I/flutter (14014): 0.0
重启后输出I/flutter (14014): wallet
I/flutter (14014): null
I/flutter (14014): null
主要代码void main() async {
WidgetsFlutterBinding.ensureInitialized();
Directory document = await getApplicationDocumentsDirectory();
Hive.registerAdapter(CurrenciesAdapter());
Hive.registerAdapter(AccountAdapter());
Hive.init(document.path);
final accountBox = await Hive.openBox<Account>('accounts');
if (accountBox.length == 0) { // default wallet
Account wallet = new Account("wallet", Currencies.USD);
accountBox.add(wallet);
}
print(accountBox.getAt(0).name.toString());
print(accountBox.getAt(0).currency.toString());
print(accountBox.getAt(0).cashAmount.toString());
runApp(MyApp());
}
帐户类别代码import 'package:hive/hive.dart';
part 'account.g.dart';
@HiveType(typeId: 0)
class Account {
@HiveField(0)
String name;
@HiveField(1)
Currencies currency;
@HiveField(2)
double cashAmount;
Account(String name, Currencies currency){
this.name = name;
this.currency = currency;
this.cashAmount = 0;
}
}
@HiveType(typeId: 1)
enum Currencies {
USD, EUR, PLN
}
最佳答案
当我向一个我很长时间没有接触过的类添加一个新字段时,我刚刚遇到了同样的问题。原来我忘记使用以下方法更新模型:
flutter pub run build_runner build
关于android - Flutter:添加到 Hive 框中的对象的字段在应用重启后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66591550/