I am using floor and getx for a flutter application, and I’m trying to inject the floor db instance via getx:
put:
import 'package:get/get.dart';
import '../database/database.dart';
Future<void> getInit() async{
await Get.putAsync<DB>(()=>DBService().init());
}
class DBService extends GetxService{
Future<DB> init() async{
final db=await $FloorDB.databaseBuilder('db.db').build();
print(db.runtimeType);
return db;
}
}
find:
final db=Get.find<DB>();
db.iconDAO.ins(IconModel(null,'/test',0,0,255,255));
however, since the type of floor db instance is the autogenerated private _$DB class which extends DB class, putting works but for finding I got an error: _TypeError (type '_$DB' is not a subtype of type 'DB' in type cast)
I tried to call Get.put
and Get.find
with dynamic type, but then i lose all editor autocompletion for DB type, and maybe compile check dont work on that too
Is there a workaround for this? thx
idkwhodatis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
GetxService
is typically used for singleton dependency injection, which fits your use case. Here’s how you should implement it:
Step 1 – Define the DBService
class DBService extends GetxService {
// Singleton access to DBService
static DBService get to => Get.find();
// Lazily initialized database instance
late final DB db;
// Asynchronous initialization of the database
Future<void> init() async {
db = await $FloorDB.databaseBuilder('db.db').build();
}
}
Step 2 – Initialize and Bind DBService
You need to bind the service before accessing DBService.to
. This is best done in the main()
function before the app runs, ensuring it’s available throughout your application.
await Get.putAsync<DBService>(
() async {
final instance = DBService();
await instance.init(); // Initialize the DB
return instance; // Return the initialized service
},
);
Step 3 – Access the Database Instance
Once the service is initialized, you can use the DBService.to
to access the database anywhere in your app.
DBService.to.db.iconDAO.ins(IconModel(null, '/test', 0, 0, 255, 255));
Once again, make sure DBService.to
is called after the service is initialized (i.e., after the putAsync()
call). If not, you’ll encounter errors related to accessing uninitialized fields.
1