[英]objects are not stored into objectbox (Flutter)
所以我试图在 ObjectBox 中保存一个对象(只有一个字符串属性)。 ObjectBox 被称为 favoriteBox。 使用 onLongPress 功能,我试图将对象放入框中。 在 initState 函数中,我试图将所有对象(更具体地说:每个对象的字符串属性)放入嵌套列表中。
我现在的问题是,在调用 onLongPress 函数并将对象放入收藏夹后,根据调试器,收藏夹为空。 我不确定我的错误在哪里。
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;
}
问题是代码不会等待 Future 在访问之前返回应用程序 Documents 目录store
。 所以store
仍然是 null 并且下面的获取一个框的行什么都不做。
getApplicationDocumentsDirectory().then((dir) {
_store = Store(getObjectBoxModel(), directory: dir.path + "/objectbox");
});
// store is still null here:
favoritesBox = _store?.box<FavoritesEntity>();
您可以将框获取代码移动到then()
闭包中。 或者,正如我们建议的那样,使用main
函数中的辅助类将 init 存储到一个全局变量中。 请参阅我们的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.