Flutter:添加到配置单元框中的对象的字段在应用程序重新启动后返回null



我正在用Flutter和Hive创建一个应用程序,但我还不熟悉它
我需要有一个初始帐户,所以我为此制作了一个配置单元框,并试图在该框中保存一个帐户对象
我检查了添加打印,它正确地将对象保存在框中。但当我重新启动应用程序时,打印不再返回值。对象仍然存在,但只有String name字段有值,其他两个字段为null
为什么某些字段在重新启动后为null?

首次运行后的输出

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

最新更新