rmawatson / flutter_isolate

Launch an isolate that can use flutter plugins.
MIT License
262 stars 80 forks source link

Can I use get_it dependency injection with flutter_isolate? #133

Closed Dev11-ultroNeous closed 1 year ago

Dev11-ultroNeous commented 1 year ago

Hi How can I use get_it dependency injection into FlutterIsolate.spawn? Error: "SyncCubit exception 'package:get_it/get_it_impl.dart': Failed assertion: line 372 pos 7: 'instanceFactory != null': Object/factory with type ProjectListUseCase is not registered inside GetIt. (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance; Did you forget to register it?)" Example :

static final ProjectListUseCase _projectListUseCase = di.getIt(); Future syncProjectData() async { final receivePort = ReceivePort(); final isolate = await FlutterIsolate.spawn( pageFetch, receivePort.sendPort); receivePort.listen((dynamic response) { if (response is String) { Log.d("Api Response $response"); } else if (response is Error) { } isolate.kill(); }); } @pragma('vm:entry-point') static void pageFetch(SendPort sendPort) async { try { int limit = 10; int page = 0; Map<String, dynamic> map = getRequestMapDataForPopupPagination(page, limit, false, ""); List items = await _projectListUseCase.getPopupDataList(page, limit, map); Log.d("SyncCubit pageFetch ${items.length}"); sendPort.send(items); } catch (e) { Log.d("SyncCubit exception ${e}"); sendPort.send("SyncCubit exception ${e}"); } }

nmfisher commented 1 year ago

I don't know about that package specifically, but anything static final in one isolate is separate from the same in another isolate. If you register an instance against your DI container in one isolate, it won't be available in the other.

Try sending the instance via the SendPort.

Dev11-ultroNeous commented 1 year ago

Thank you @nmfisher