4

Everything works fine until I restart the app (close the app and open it) and can not see previously saved data, but if I check the box status it is opened and empty. Am I doing something wrong?

  • Running on real device Xiaomi Redmi 4A (actually the problem appears also on Iphone devices)
  • Working on Mac M1
  • Flutter (Channel stable, 2.2.2, on macOS 11.2 20D64 darwin-arm, locale ru)
  • I found "problem" in github repo but there is nothing useful

main.dart

void main() async {
  // init hive
  WidgetsFlutterBinding.ensureInitialized();
  await lds.init();
  // init app
  runApp(MyApp());
}

hive init file

Future<void> init() async {
  final appDocumentDirectory = await path.getApplicationSupportDirectory();
  Hive.init(appDocumentDirectory.path);

  // registering entities
  Hive.registerAdapter(ItemModelAdapter());
}

save and load functions

class ItemLocalDataSource {
  static const String BOX_ITEMS = 'item-models';

  Future<List<ItemModel>> getLocalItems() async {
    await Hive.openBox(BOX_ITEMS);
    final box = Hive.box(BOX_ITEMS);
    final items = box.get(0) as List<ItemModel>;
    return items;
  }

  Future<void> setLocalItems(List<ItemModel> items) async {
    await Hive.openBox(BOX_ITEMS);
    final box = Hive.box(BOX_ITEMS);
    box.put(0, items);
    print('saved $items');
  }
}

package versions I am using in pubspec.yaml

  # hive (local data storage)
  hive: ^1.4.4+1
dev_dependencies:
  flutter_test:
    sdk: flutter
  # hive adapter generator
  hive_generator: ^0.8.2
  # build runner
  build_runner:
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
1encore
  • 394
  • 4
  • 15

2 Answers2

1

When I have upgraded Dart SDK , app have caused the same issue. When I have downgraded the Dart SDK, Hive started working as expected. Solution is downgrading Dart SDK. My current SDK is:

Dart SDK version: 2.14.2 (stable) 
  • Hi how do I change the dart sdk version? – Dean Villamia Oct 07 '21 at 08:19
  • 1
    @Dean Villamia I have rolled back my files with github, but don't know what to do to change the dart sdk. You can try to change sdks part in pubspec.lock, which I remember after changing this file it have been worked. `sdks: dart: ">=2.14.0 <3.0.0" flutter: ">=2.5.0` it should be something like that – Shahzod O'ralov Oct 08 '21 at 21:55
-1

This worked for me https://blog.logrocket.com/handling-local-data-persistence-flutter-hive/

For some reason the Model wasn't handling the late keyword I think? Feel free to correct me in the comments as I would also like to learn :D

Dean Villamia
  • 576
  • 11
  • 24