4

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
}

  • 2
    The problem was solved. I've been using my own enum Currencies type and I've created wrong Hive type. It isn't enough to write it like in the code above. Every single enumeration need to have its own @HiveField(index). After adding that, all the data are now loaded correctly after restarting the application. Here is an example: https://www.codegrepper.com/code-examples/dart/flutter+hive+enum – CupOfCoffee Mar 12 '21 at 14:34

1 Answers1

3

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
finisinfinitatis
  • 861
  • 11
  • 23
  • This helped! Such an uninformative thing to debug: my listenable() was working alright at first, and then returned an empty object without error – vladli Nov 16 '22 at 22:52