0

I'm trying to use ObjectBox as the database in a flutter application. The following is the sample code.

However, while execution I was returned with the error of "_store is not initialized".

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

  ...
}```

1 Answers1

0

initialize the databases in the main one and then you pass the store to the HomePage, that is why it tells you that error '_store no se inicializa'. You must declare your global store and then you pass it to each view.

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

this is the simple way to connect with Object box