objects are not stored into objectbox (Flutter)

1k Views Asked by At

So Im trying to save an object(with only one String attribute) in the ObjectBox. The ObjectBox is called favoriteBox. With the onLongPress-function im trying to put the object in the box. In the initState-function im trying to put all the objects (more specific: the string attributes of each object) in to a nested list.

My problem now is that after calling the onLongPress-function and putting the object in the favoriteBox, the favoritBox is null according to the Debugger. Im not sure where my mistake is.

class _GridViewJokesState extends State<GridViewJokes> {
  late int seasonsListIndex;
  List<List<String?>> seasonsList = seasons;

  final toast = FToast();
  final AudioPlayer audioPlayer = AudioPlayer();
  late SeasonProvider seasonProvider;

  Store? _store;
  Box<FavoritesEntity>? favoritesBox;

  @override
  void initState() {
    super.initState();
    toast.init(context);
    getApplicationDocumentsDirectory().then((dir) {
      _store = Store(getObjectBoxModel(), directory: dir.path + "/objectbox");
    });
    favoritesBox = _store?.box<FavoritesEntity>();
    seasonsList[5] =
        favoritesBox?.getAll().map((e) => e.quoteName).toList() ?? [];
  }
void onLongPress(listTileIndex) {
    if (seasonProvider.seasonPicked) {
      seasonsList[5].add(seasonsList[seasonsListIndex][listTileIndex]);
      favoritesBox?.put(FavoritesEntity(
          quoteName: seasonsList[seasonsListIndex][listTileIndex]));
      toast.showToast(
          child: buildToast("Zu Favoriten hinzugefügt"),
          gravity: ToastGravity.BOTTOM);
    }
import 'package:objectbox/objectbox.dart';

@Entity()
class FavoritesEntity {
  FavoritesEntity({required this.quoteName});

  int id = 0;
  String? quoteName;

}
1

There are 1 best solutions below

0
On

The issue is that the code does not await the Future that returns the application Documents directory before accessing store. So store will still be null and the following line that gets a box does nothing.

getApplicationDocumentsDirectory().then((dir) {
  _store = Store(getObjectBoxModel(), directory: dir.path + "/objectbox");
});
// store is still null here:
favoritesBox = _store?.box<FavoritesEntity>();

You can either move the box get code into the then() closure. Or, as we recommend, init Store into a global variable using a helper class in the main function. See our examples.