Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how can i set state in static method? i get an error which is 'instanceFactory != null': Object/factory #145

Closed
yakupbaser opened this issue Jan 8, 2021 · 17 comments

Comments

@yakupbaser
Copy link

hi to all. i use foreground_service plugin & stacked(state management lib) & get_it and foreground_service needs a static periodicfunction that i use a static service class in it. But when i use static class with stacked plugin, the app is working but i cant manage the state which in my static class. So how to manage state in static class, how can i use get_it & static class & states together?

my static service class is:

 @lazySingleton
class IlanService with ReactiveServiceMixin {
  static IlanService _ilanService;
  factory IlanService() {
    if (_ilanService == null) {
      _ilanService = IlanService._internal();
      return _ilanService;
    } else {
      return _ilanService;
    }
  }
  Ilan _ilan = Ilan();
  Ilan get ilan => _ilan;
  Future<void> updateIlan() async {
  _ilan = await databaseHelper.getIlan(mazagaService.magazaID);
  notifyListeners();
}

locator.dart:

import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'locator.config.dart';
final getIt = GetIt.instance;
@InjectableInit(
  initializerName: r'$initGetIt', // default
  preferRelativeImports: true, // default
  asExtension: false, // default
)
void configureDependencies() => $initGetIt(getIt);

main.dart:

void main() async{
  configureDependencies();
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

myview.dart which has the periodic function fore foreground_service:

.
..
...
import 'package:buybox/app/services/ilan_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_foreground_service_plugin/flutter_foreground_service_plugin.dart';
import 'package:stacked/stacked.dart';
import 'package:buybox/datamodels/ilan_model.dart';
IlanService ilanService = IlanService();
/* if i try final ilanService = getIt<IlanService>(); then i get an error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:get_it/get_it_impl.dart': Failed assertion: line 298 pos 9: 'instanceFactory != null': Object/factory with  type IlanService is not registered inside GetIt.
E/flutter (26306): (Did you accidentally do  GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
E/flutter (26306): Did you forget to register it?)
*/
void periodicTaskFun() {
  FlutterForegroundServicePlugin.executeTask(() async {
  ..
  ..
  ...
  await ilanService.updateIlan();
  await FlutterForegroundServicePlugin.refreshForegroundServiceContent(
    notificationContent: NotificationContent(
      iconName: 'ic_launcher',
      titleText: 'Title Text',
      bodyText: '${DateTime.now()}',
      subText: 'subText',
      color: Colors.red,
    ),
  );
});

and lastly i added locator.config.dart:

// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// InjectableConfigGenerator
// **************************************************************************
import 'package:stacked_services/stacked_services.dart';
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'services/fiyat_service.dart';
import 'services/third_party_services_module.dart';
/// adds generated dependencies
/// to the provided [GetIt] instance
GetIt $initGetIt(
  GetIt get, {
  String environment,
  EnvironmentFilter environmentFilter,
}) {
  final gh = GetItHelper(get, environment, environmentFilter);
  final thirdPartyServicesModule = _$ThirdPartyServicesModule();
  gh.lazySingleton<IlanService>(() => IlanService());
  // Eager singletons must be registered in the right order
  gh.singleton<DialogService>(thirdPartyServicesModule.dialogService);
  return get;
}
class _$ThirdPartyServicesModule extends ThirdPartyServicesModule {
  @override
  DialogService get dialogService => DialogService();
}

so how can i use final ilanService = getIt(); instead of IlanService ilanService = IlanService(); Bcoz i have to set state in it :( (edited)

@escamoteur
Copy link
Collaborator

My guess is that you call

final ilanService = getIt<IlanService>();

before your registration is finished.
is final ilanService a global variable?

@yakupbaser
Copy link
Author

yes it is global variable

@escamoteur
Copy link
Collaborator

Yeah there is the problem. Why do you use a global variable here and not access get_it when you need it?

@yakupbaser
Copy link
Author

bcoz periodicTaskFun need it?

@escamoteur
Copy link
Collaborator

you can call Getit inside a static function

@yakupbaser
Copy link
Author

so should i register service class in static function whith getIt?

@escamoteur
Copy link
Collaborator

Why registering in the static function? just use it in there with getIt<IlanService>()

@yakupbaser
Copy link
Author

yakupbaser commented Jan 8, 2021

i made your said but i get same error:

`void periodicTaskFun() {

FlutterForegroundServicePlugin.executeTask(() async {

final staticIlanService = getIt<IlanService>()

dbIlanList = await staticIlanService.getIlanListWithoutRender();

.
..
...
await FlutterForegroundServicePlugin.refreshForegroundServiceContent(
  notificationContent: NotificationContent(
    iconName: 'ic_launcher',
    titleText: 'Title Text',
    bodyText: '${DateTime.now()}',
    subText: 'subText',
    color: Colors.red,
  ),
);

});`

error is:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:get_it/get_it_impl.dart': Failed assertion: line 298 pos 9: 'instanceFactory != null': Object/factory with type DatabaseHelper is not registered inside GetIt. E/flutter (15573): (Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance; E/flutter (15573): Did you forget to register it?)

@escamoteur
Copy link
Collaborator

could I clone your project and have a closer look?

@yakupbaser
Copy link
Author

yakupbaser commented Jan 8, 2021

i created a clear project for this issue. There is a counter text in the form. When i click the Increase State From HomeViewModal its success. But When i click the Start ForeGround Service; it doesnt set the Text widget and if i use getit i get same error:

final newExampleService = getIt<ExampleService>();

https://github.com/yakupbaser/demogetit

@escamoteur
Copy link
Collaborator

It didn't crash here. can you push the version that crashes?

@yakupbaser
Copy link
Author

yakupbaser commented Jan 8, 2021

yes it did not crash becoz i use ExampleService newExampleService = ExampleService(); in periodicTaskFun of home_view.dart. if you try final newExampleService = getIt<ExampleService>(); then you can see the crash

//i pushed crashed build repo

@escamoteur
Copy link
Collaborator

Ok, it has nothing to do with the ststic method, the problem is that your periodic function is called from a different Isolate which has its own global variables, which means there also is a GetIt but it's a different instance than theone you register your objects in.

Do you need to have this running on a different Isolate? would a normal Timer not be enough?

I also doubt that you need that static stuff in your example service. Important is for this plugin that your periodic function is either gloibal or static.

@yakupbaser
Copy link
Author

periodicTaskFun of foreground service is working when app is closed but timer is not :(

@escamoteur
Copy link
Collaborator

ah, I see. Then I fear you have to instanciate your Objects there manually. It doesn't look like you can pass over any data to the functionthat is called.

@yakupbaser
Copy link
Author

even so thanks for your helps :)

@escamoteur
Copy link
Collaborator

Thanks, spread the word about get_it, check out get_it_mixin and I'm always happy of a nice tweet @thomasburkhartb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants