[英]where should we initialize ObjectBox Store with navigation 2.0 in flutter?
[英]ObjectBox database not initializing in Flutter 2.0
我正在尝试使用 ObjectBox 作为颤振应用程序中的数据库。 以下是示例代码。
但是,在执行时,我返回了“_store 未初始化”的错误。
class _HomePageState extends State<HomePage> {
...
// 👇 ADD THIS
late Stream<List<ShopOrder>> _stream;
@override
void initState() {
super.initState();
setNewCustomer();
getApplicationDocumentsDirectory().then((dir) {
_store = Store(
getObjectBoxModel(),
directory: join(dir.path, 'objectbox'),
);
setState(() {
// 👇 ADD THIS
_stream = _store
.box<ShopOrder>()
// The simplest possible query that just gets ALL the data out of the Box
.query()
.watch(triggerImmediately: true)
// Watching the query produces a Stream<Query<ShopOrder>>
// To get the actual data inside a List<ShopOrder>, we need to call find() on the query
.map((query) => query.find());
hasBeenInitialized = true;
});
});
}
...
}```
在主数据库中初始化数据库,然后将商店传递给主页,这就是为什么它会告诉您错误“_store no se inicializa”。 您必须声明您的全局存储,然后将其传递给每个视图。
late Store _stores;
void main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyState createState() => _MyState();
}
class _MyState extends State<MyApp> {
bool iniciando_store = true;
@override
void initState() {
super.initState();
initPlatformState();
getApplicationDocumentsDirectory().then((directory) {
_stores = Store(
getObjectBoxModel(),
directory: join(directory.path, 'objectbox')
);
setState(() {
iniciando_store = false;
});
});
}
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ThemeProvider()),
],
child: Consumer<ThemeProvider>(builder: (context, theme, snapshot) {
return MaterialApp(
title: 'Object box title',
home: !iniciando_store
? MyHomePage(
title: "Home", loadingSore: iniciando_store, STORE: _stores)
: MyStatefulWidget());
}),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage(
{Key? key,
required this.title,
required this.loadingSore,
required this.STORE})
: super(key: key);
final String title;
final Store STORE;
final bool loadingSore;
@override
_MyHomePageState createState() => _MyHomePageState();
}
这是连接对象框的简单方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.