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;
      });
    });
  }

  ...
}```
4

1 回答 1

0

在主数据库中初始化数据库,然后将商店传递给主页,这就是为什么它会告诉您错误“_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();
    }

这是连接对象框的简单方法

于 2021-10-13T19:57:13.900 回答