Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: fields of an object added to a Hive box returns null after app restart

I'm creating an app with Flutter and Hive but I'm not familiar with it yet.
I need to have an initial account in it, so I've made a Hive box for that and I'm trying to save an account object in that box.
I check adding with prints and it saved the object in box correctly. But when I restart the app, the print no longer returns the values. Object is still there, but only the String name field has a value, and the other two are nulls.
Why some fields are nulls after the restart?

Output after first run

I/flutter (14014): wallet
I/flutter (14014): Currencies.USD
I/flutter (14014): 0.0

Output after restart

I/flutter (14014): wallet
I/flutter (14014): null
I/flutter (14014): null

Main code

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());
}

Account class code

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
}

like image 658
CupOfCoffee Avatar asked Nov 05 '25 08:11

CupOfCoffee


1 Answers

I have just run into the same issue when I added a new field to a class which I didnt touch for a very long time. Turned out I forgot to update the model using:

flutter pub run build_runner build
like image 165
finisinfinitatis Avatar answered Nov 07 '25 09:11

finisinfinitatis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!