Injecting floor database dependency through GETX is not working : Flutter

514 Views Asked by At

I am new at using Getx for state management. I am trying to inject the dependency of my DB instance in main by Getx through initial binding I am using the floor database. can anyone help me with this. where I went wrong?

this is how my register function looks like

void registerdbInstance() {
  Get.lazyPut(<AppDatabase>() async =>
      {await $FloorAppDatabase.databaseBuilder('app_database.db').build()});
}

this is how my main app widget looks like

 @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: appName,
      initialBinding: BindingsBuilder.put(() => registerdbInstance),
      theme: ThemeData(
        fontFamily: 'Montserrat',
        backgroundColor: sdWhiteColor,
        colorScheme: ColorScheme.fromSwatch()
            .copyWith(primary: sdPrimaryColor, secondary: sdSecondaryColor),
      ),
      getPages: routeList,
      home: ServiceDeskHome(),
    );

initialBinding: BindingsBuilder.put(() => registerdbInstance),

this is how I am trying to access this dependency

var db = Get.find();

The problem is that Getx is not able to find the dependency.

"AppDatabase" not found. You need to call "Get.put(AppDatabase())" or "Get.lazyPut(()=>AppDatabase())"

2

There are 2 best solutions below

0
On BEST ANSWER

I initialized it in this way. it will initialize when the app starts, you can use it later anywhere by simply calling Get.find()

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Get.putAsync<AppDatabase>(permanent: true, () async {
    final db = await $FloorAppDatabase
        .databaseBuilder('todotask.db')
        .build();
    return db;
  });
  await GetStorage.init();
  runApp(const MyApp());
}
2
On

If i recall corectly when you are working with databases in getx you have to do it asynchronously and use Get.putAsync if you want to register an asynchronous instance (LINK). I would consider using fenix parameter as well.