Git Product home page Git Product logo

fluttercommunity / get_it Goto Github PK

View Code? Open in Web Editor NEW
1.3K 1.3K 136.0 1.13 MB

Get It - Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App. Maintainer: @escamoteur

Home Page: https://pub.dev/packages/get_it

License: MIT License

Dart 78.76% Objective-C 0.02% Batchfile 0.08% Kotlin 0.06% Swift 0.53% CMake 8.62% C++ 10.43% C 0.66% HTML 0.85%

get_it's Introduction

Flutter Community

Flutter Community

A central place for community made Flutter content.


The Flutter Community is an organization aimed at providing a central place for community made Flutter packages and content to live.

Our goal is to ensure packages made by the Flutter community are kept alive and maintained in one place.

Medium Articles

To go along with the packages, we have started a Medium publication as a central location for community content to be published - especially if it relates to the packages here.

https://medium.com/flutter-community

Packages

These are the packages featured on the Flutter Community.

Name Release Description Maintainer
android_alarm_manager_plus Pub Flutter plugin for accessing the Android AlarmManager service, and running Dart code in the background when alarms fire. Miguel Beltran
android_id Pub Flutter plugin for retrieving the Android ID. Not supported on iOS. Joachim Nohl
android_intent_plus Pub Flutter plugin for launching Android Intents. Not supported on iOS. Miguel Beltran
app_review Pub Request and Write Reviews and Open Store Listing for Android and iOS in Flutter. Rody Davis
backdrop Pub Backdrop implementation in dart. (https://material.io/design/components/backdrop.html) Harsh Bhikadia
breakpoint Pub A Flutter plugin to calculate the material design breakpoints. Rody Davis
sealed_unions Pub Sealed Unions for Dart George Medve
firestore_helpers Pub Firestore helper function to create dynamic and location based queries Thomas Burkhart
draggable_scrollbar Pub A scrollbar that can be dragged for quickly navigation through a vertical list. Additional option is showing label next to scrollthumb with information about current item. Marina Kuznetsova
after_layout Pub Execute code after the first layout of your widget has been performed, i.e. after the first frame has been displayed. Simon Lightfoot
flutter_blurhash Pub Compact representation of a placeholder for an image. Encode a blurry image under 30 caracters for instant display like used by Medium Robert Felker
contacts_service Pub A Flutter plugin to retrieve and manage contacts on Android and iOS devices. Lukas Dickie
flutter_downloader Pub A plugin for creating and managing download tasks. Supports iOS and Android. Hung Duy Ha
flutter_google_places Pub Google places autocomplete widgets for flutter. No wrapper, use https://pub.dartlang.org/packages/google_maps_webservice Kev Morelli
infinite_listview Pub ListView with items that can be scrolled infinitely in both directions. Simon Lightfoot
flutter_launcher_icons Pub A package which simplifies the task of updating your Flutter app's launcher icon. Mark O'Sullivan
flutter_sms Pub A Flutter plugin to Send SMS and MMS on iOS and Android. If iMessage is enabled it will send as iMessage on iOS. This plugin must be tested on a real device on iOS. Rody Davis
sticky_headers Pub Flutter Sticky Headers - Lets you place headers on scrollable content that will stick to the top of the container whilst the content is scrolled. Simon Lightfoot
flutter_uploader Pub A plugin for creating and managing upload tasks with optional background exection support. Sebastian Roth
wear Pub A plugin that offers Flutter support for Wear OS by Google NO MAINTAINER PROVIDED
flutter_webview_plugin Pub Plugin that allow Flutter to communicate with a native Webview. Rafal Wachol
flutter_whatsnew Pub A new Flutter package to show updates to users. Rody Davis
workmanager Pub Flutter Workmanager. This plugin allows you to schedule background work on Android and iOS. NO MAINTAINER PROVIDED
font_awesome_flutter Pub The Font Awesome Icon pack available as Flutter Icons. Provides 1500 additional icons to use in your apps. Brian Egan
get_it Pub Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App" Thomas Burkhart
get_version Pub Get the Version Name, Version Code, Platform and OS Version, and App ID on iOS and Android. Rody Davis
import_sorter Pub Automatically sort all your dart imports. Support for any dart project. Matthew Gleich
native_widgets Pub A new Flutter package for using Android and iOS natively on each platform. Rody Davis
page_turn Pub Page Turn Widget - Add a page turn effect to widgets in your app. Rody Davis
persist_theme Pub A flutter plugin for persisting the theme data. Support for Dark Mode. Rody Davis
redux Pub Redux is a predictable state container for Dart and Flutter apps John Ryan
redux_undo Pub Make your redux store undo- and redoable. Inspired by the JS redux_undo package. Michel Engelen
responsive_scaffold Pub On mobile it shows a list and pushes to details and on tablet it shows the List and the selected item. Rody Davis
rx_command Pub Reactive event handler wrapper class inspired by ReactiveUI. Thomas Burkhart
state_persistence Pub Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications data directory. Simon Lightfoot

Submitting your packages

If you'd like to submit your package to the Flutter Community GitHub organization, please see the Flutter Community Transfer Guide.

Getting in contact

For any questions regarding the Flutter Community, please open an issue on the /community repository.

Note to packages owners

Flutter Community aims to bring the best community-made packages forward. Because of this, not all proposed packages will be accepted.

get_it's People

Contributors

ae-mc avatar anaisbetts avatar bryanx avatar bvoq avatar escamoteur avatar ewertonrp avatar fzyzcjy avatar geisterfurz007 avatar hughesjs avatar isinghmitesh avatar jhionan avatar kasefuchs avatar kishanhitk avatar kmartins avatar lacopiroty avatar lukepighetti avatar miyoyo avatar mondoktamas avatar mrjosch avatar n3wtron avatar nilsreichardt avatar noordawod avatar olexale avatar rexios80 avatar selcukguvel avatar sspatari avatar tactical-retreat avatar tpucci avatar usamakarim avatar venkata-reddy-dev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

get_it's Issues

using get_it in separated classes

you suppose your sample code witch all of classes in one class as main, separated in some other class into another files, for example:

main
MyApp 
MyHomePage 
_MyHomePageState 

in this structure how can i get_it witch that defined in main() ? how can i registered classes in all of other classes?

increase the max number of params for factories

thank you the adding the ability to create factories that accept parameters. but right now they only accept 2 parameters at maximum which is an unnecessary limitation by my account. please increase that number or remove this limitation

Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized

Hi @escamoteur and thank you for your talk last week in Köln :) so I decided to give get_it a try but unfortunately got into troubles.

How can I use AuthService inside of ExpertService?

// main.dart

import 'package:my-app/features/utils.dart';

void main() {
  registerServices();
  runApp(App());
}
// utils.dart

import 'package:get_it/get_it.dart';

final GetIt getIt = GetIt.I;

void registerServices() {
  getIt.registerSingleton(AuthService());
  getIt.registerSingleton(NavService());
  getIt.registerSingleton(ExpertService());
}
// auth.service.dart

import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  FirebaseAuth _auth = FirebaseAuth.instance;

  Stream<FirebaseUser> get firebaseUser$ => _auth.onAuthStateChanged;

  void signIn(String email, String password) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
    } catch (e) {
      print('!!! ${e.message} !!!');
    }
  }
}
// expert.service.dart

import 'package:rxdart/rxdart.dart';
import 'package:my-app/core/services/database/database.service.dart';
import 'package:my-app/features/auth/auth.service.dart';
import 'package:my-app/features/expert/expert.model.dart';
import 'package:my-app/features/utils.dart';

// DatabaseService handles document reads and writes
class ExpertService extends DatabaseService<Expert> {
  Stream<Expert> get model$ => FirebaseAuth.instance.onAuthStateChanged
      .switchMap((user) => user == null ? Stream.empty() : getData$(user.uid));

  ExpertService() : super('experts');
}

The error :(

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized
If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
#0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:76:7)
#1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:89:4)
#2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
#3      MethodChannel.setMethodCallHandler (package:flutter/src/services/platform_channel.dart:375:5)
#4      new MethodChannelFirestore (package:cloud_firestore_platform_interface/src/method_channel/method_channel_firestore.dart:27:13)
#5      FirestorePlatform.instance (package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart:62:19)
#6      new Firestore (package:cloud_firestore/src/firestore.dart:26:42)
#7      Firestore.instance (package:cloud_firestore/src/firestore.dart:29:36)
#8      new DatabaseService (package:my-app/core/services/database/database.service.dart:8:41)
#9      new ExpertService (package:my-app/features/expert/expert.service.dart)
#10     registerServices (package:my-app/features/utils.dart:13:27)
#11     main (package:my-app/main.dart:11:3)
#12     _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:239:25)
#13     _rootRun (dart:async/zone.dart:1126:13)
#14     _CustomZone.run (dart:async/zone.dart:1023:19)
#15     _runZoned (dart:async/zone.dart:1518:10)
#16     runZoned (dart:async/zone.dart:1502:12)
#17     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:231:5)
#18     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:307:19)
#19     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

Thank you in advance and I hope you can help me!

registerLazySingleton unexpected behavior

This does NOT WORK,
GetIt.I.registerLazySingleton(() => SingletonInjector.configuration(RepoType.PROD));

ERROR,
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following ArgumentError was thrown building Builder(dirty):
Invalid argument (Object of type Injector is not registered inside GetIt.
Did you forget to pass an instance name?
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;)): Instance
of '_Type'

But this WORKS,
Injector inj = SingletonInjector.configuration(RepoType.PROD);
GetIt.I.registerLazySingleton(() => inj);

How I can get a lazySinglton from another isolate

suppose I registered a repo like this

sl.registerLazySingleton<CalenderMonthRepository>(()=>CalenderMonthRepositoryImpl(
   local: sl(),
   remote: sl(),
   location: sl(),
   notificationsDataSource: sl(),

all local, remote,location and notificationsDataSource are lazySingletons too,

I have this static function

static Future<CalenderMonth> getCalenderMonth(CalenderMonthRepository repository ) async{
//use repository
  }

and I am calling compute function like this

CalenderMonth calenderMonth= await compute(getCalenderMonth,repository);

the issue is when I pass it to another isolate via dart compute function which should run on another isolate I get error of not reachable code .

the question is how to use lazySingletons like these on other isolates ?

Question: Is GetIt capable of changing singleton in runtime?

Is it possible to dynamically change object in runtime using GetIt. For example:
Let's say that there is abstract class DataSource, with two concrete implementation, LocalDataSoruce and NetworkDataSource. Is it possible to make GetIt return one or the other service depending on configuration that user can set in runtime?

Thanks

How to get reference of the container deep in tree?

Hi

Thanks for this great work of bringing IoC/Locator to Dart. I have a question, how can I get the reference of GetIt in which I have registered few classes on the different page? For example, in app.dart I have created GetIt instance and registered some classes in main() method, now I need this GetIt instance in one of my entry page let say userEditView.dart, how should I get it? I don't want to use InheritedWidget.

Thanks,
Binoy

Avoid dispose singleton

Hi, I need help with an issue.
I observed that when the app go to background the Singleton are disposed.
It is possibile to avoid dispose singleton on app background?

Thanks in advance

[Feature Request] Get if registered, else, register then get

Hi, I'm looking for a GetIt version of this pseudocode

var myClass = GetIt.instance.get<MyClass>(orElse: (){
   // automatic registration of the return value of this method.
  return MyClass();
});

Use case:

To avoid this Exception instead of using try/catch:

"Object with name $instanceName is not registered inside GetIt"

The only potential issue I foresee is how will GetIt know how you want to register this instance.

Could not resolve the package 'get_it' in 'package:get_it/get_it.dart

I have included the package in pubspec.yaml file :

dependencies:
  flutter:
    sdk: flutter
  core:
   path: ../core

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  shared_preferences: ^0.5.6
  flutter_bloc: ^3.0.0
  equatable: ^1.0.3
  url_launcher: ^5.4.1
  get_it: ^3.1.0

  flutter_localizations:
    sdk: flutter

I have also tried doing flutter clean and deleting all builds and re running pub get but still same error that it can't resolve get_it.

Compiler message: Error: Could not resolve the package 'get_it' in 'package:get_it/get_it.dart'. core/lib/locator.dart:2:8: Error: Not found: 'package:get_it/get_it.dart' import 'package:get_it/get_it.dart' show GetIt; ^ core/lib/locator.dart:4:1: Error: Type 'GetIt' not found. GetIt locator = GetIt.instance; ^^^^^ core/lib/locator.dart:4:1: Error: 'GetIt' isn't a type. GetIt locator = GetIt.instance; ^^^^^ core/lib/locator.dart:4:17: Error: Getter not found: 'GetIt'. GetIt locator = GetIt.instance; ^^^^^ Unhandled exception: FileSystemException(uri=org-dartlang-untranslatable-uri:package%3Aget_it%2Fget_it.dart; message=StandardFileSystem only supports file:* and data:* URIs) #0 StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:33:7) #1 asFileUri (package:vm/kernel_front_end.dart:604:37) #2 writeDepfile (package:vm/kernel_front_end.dart:799:21) <asynchronous suspension> #3 FrontendCompiler.compile (package:frontend_server/frontend_server.dart:472:15) <asynchronous suspension> #4 _FlutterFrontendCompiler.compile (package:flutter_frontend_server/server.dart:38:22) #5 starter (package:flutter_frontend_server/server.dart:149:27) #6 main (file:///b/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:8:30) #7 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:32) #8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12) Target kernel_snapshot failed: Exception: Errors during snapshot creation: null build failed. FAILURE: Build failed with an exception. * Where: Script '/Users/nateshmbhat/Apps/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 780 * What went wrong: Execution failed for task ':flutter:compileFlutterBuildDebug'. > Process 'command '/Users/nateshmbhat/Apps/flutter/bin/flutter'' finished with non-zero exit value 1 * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 34s Finished with error: Gradle task assembleDebug failed with exit code 1

Using singletone inside other singletone leads to error

I have 2 singletones. First is for user preferences and second is for connection with server.
Inside WampService (connection singletone) i am implementing InternalSettings (preferences singletone) like this:
InternalSettings mInternalSettings = locator<InternalSettings>();

My setup locator looks like this:

void setupLocator() async {
  var iSettingsInstance = await InternalSettings.getInstance();
  var iWampInstance = await WampService.getInstance();
  locator.registerSingleton<InternalSettings>(iSettingsInstance);
  locator.registerSingleton<WampService>(iWampInstance);
}

Is there some way to implement singletones, which ones also depends from other singletones?
Error message is inside WampService file, where i am using locator: InternalSettings is not registered inside GetIt.

registerFactoryParam does not allow subclasses for param types?

It looks like registerFactoryParam() does not allow invocation of the factory function in which one of the parameters is an object that is a subclass of the defined parameter type. Is my understanding correct, and is this expected behavior? Should I be using some other method instead?

For instance, I register my factory like so:

  getIt.registerFactoryParam<PackStoreDetails, PackStore, void>(
    (param1, param2) => buildStoreDetails(param1, param2),
  );

PackStore is a simple class that is extended by PackStoreModel, and an instance of the latter is passed to the factory method, at which point I get this error:

Assertion failed:
file:///Users/nfiedler/flutter/.pub-cache/hosted/pub.dartlang.org/get_it-4.0.1/lib/get_it_impl.dart:108:17
param1 == null || param1.runtimeType == param1Type
"Incompatible Type passed as param1\nexpected: PackStore actual: PackStoreModel"

Thanks

Get_it best practice

Should I use in GetIt getIt = new GetIt(); in every widget file or should import a dat file where I created the instance?

dependsOn confusion

I'm a bit confused on the dependsOn syntax. Before I was using readyFuture and that worked fine but I decided to try the new beta version. Here's how I register my singletons.

  getIt.registerSingletonAsync<AndroidDetails>(
    (_) => AndroidDetailsImplementation()..init(),
  );
  getIt.registerSingletonAsync<ThemeService>(
    (_) => Future<ThemeService>.value(ThemeService()),
    dependsOn: <Type>[AndroidDetails],
  );

I keep getting The method <method name> was called on null since I'm using _details.<method name>().

Here's my ThemeService constructor:

  ThemeService() {
    _details = getIt.get<AndroidDetails>();
    settings = Hive.box<dynamic>(DatabaseHelper.SETTINGS_BOX);
  }

Am I doing something wrong? Should I be using getAsync?

EDIT: Here's my AndroidDetailsImplementation init() function:

  Future<void> init() async {
    try {
      final AndroidDeviceInfo _deviceInfo = await DeviceInfoPlugin().androidInfo;
      _deviceData = getDeviceData(_deviceInfo);
    } on PlatformException {
      _deviceData = <String, dynamic>{
        'Error:': 'Failed to get platform version.',
      };
    }
  }

Prints class names on start

I register a couple of lazy singletons before the app is started.

void setupLocators() {
  locator.registerLazySingleton(() => DatabaseService());

  locator.registerLazySingleton(() => Foo());
  locator.registerLazySingleton(() => Bar());
}
void main() {
  setupLocators();
  runApp(MultiProvider(
    providers: <SingleChildWidget>[
      ChangeNotifierProvider.value(value: locator<Foo>()),
      ChangeNotifierProvider.value(value: locator<Bar>()),
    ],
    child: App(),
  ));
}

But the package seems to print the name of each registered lazy singleton to the console at the same time.

I/flutter (21761): DatabaseService
I/flutter (21761): Foo
I/flutter (21761): Bar

@named()

Hi! It's very nice library. Could you add @named() function? Thanks!

Example

`injector.registerLazySingleton(() => Client(), name: "Client1");
injector.registerLazySingleton(() => Client(), name: "Client2");

final client1 = injector.get("Client1");
final client2 = injector.get("Client2");`

Allow for UnitOfWork Scoping

I really like the simplicity of get_it and it's speed.
Thank you so much for creating and maintaining this product!

I am wondering if we can get the ability to do UnitOfWork scoping where even factories will be the same instance if used in the same UnitOfWork.

See the code below for the example:

Registration

GetIt.I.registerFactory<SharedService>(() => new SharedService());
GetIt.I.registerFactory<Service3>(() => new Service3(GetIt.I.get<SharedService>()));
GetIt.I.registerFactory<Service2>(() => new Service2(GetIt.I.get<SharedService>()));
GetIt.I.registerFactory<MainService>(() => new MainService(GetIt.I.get<Service2>(), GetIt.I.get<Service3>()));

Classes

class MainService(Service2 service2, Service3 service3)
class Service2(SharedService sharedService)
class Service3(SharedService sharedService)

Test

var service1 = GetIt.I.get<MainService>();
        expect(service1.service2.service4, same(service1.service3.service4));

Can SharedService be the same instance in this unitOfWork without making it a singleton?

Retrieval by instance name does not work

Consider this simple example:

void main() {
  try {
    var sl = GetIt.instance;

    sl.registerSingleton("some String", instanceName: "foo");

    final x = sl<String>("foo");
  } catch (e) {
    print(e);
  }
}

This fails with this output:

String
Invalid argument(s): Object with name foo has a different type (String) than the one that is inferred (String) where you call it

I think the problem is this code:

    if (registeredObject.registrationType is! T) {
      print(T.toString());
      throw ArgumentError(
          "Object with name $instanceName has a different type (${registeredObject.registrationType.toString()}) than the one that is inferred (${T.toString()}) where you call it");
    }

registrationType has a type of Type so this code is asking whether an instance of Type has the type String and the answer is of course no. I think you want to replace is! with !=.

Example not working on 2.0.1

Tried to run the example with version 2.0.0 or 2.0.1 and it did not. It just appears a white screen. Also, this error appears when running the example:

"Unhandled Exception: 'package:get_it/get_it.dart': Failed assertion: line 33 pos 12: 'allowMultipleInstances': You should prefer to use the instance() method to access an instance of GetIt. If you really need more than one GetIt instance please set allowMultipleInstances to true."

Went back to 1.1.0 and changed GetIt.asNewInstance() to GetIt() and now it works normally.

Registering as dynamic

Hi thanks for the work, this is exactly what I was looking for.

I am tinkering with this and ran some unit tests. Basically calling getIt.registerFactory<Hello>(() => new Hello()); registered Hello as dynamic so it fails when doing getIt.get<Hello>() plus it throws if I add something else because dynamic has already been registered.

What am I missing?

registerFactoryParam does not allow List<whatever> params

It seems that providing a List of a class does not work with registerFactoryParam.
There error shown is

Incompatible Type passed as param1
expected: List<FilterBucket> actual: List<FilterBucket>
'package:get_it/get_it_impl.dart':
Failed assertion: line 108 pos 17: 'param1 == null || param1.runtimeType == param1Type'
4:36

version: 4.0.1

Quick question: does storing BuildContext in get_it causes a memory leak?

I'm registering a singleton with FirebaseMessagingHelper class in get_it so I can have access to its instance throughout the code, which is really useful.

But there are some callbacks where I want to open new pages in my Flutter app. For this, I need a context.

Is it ok to pass and store a BuildContext there and keep it as a singleton in get_it? Would it cause a memory leak (like in plain Android for example)?

What I want to do is to initialize my FirebaseMessagingHelper and pass there a BuildContext from the MyApp stateful widget, then I register it as a Singleton.

GetIt.instance
      .registerSingleton<FirebaseNotificationsHelper>(FirebaseNotificationsHelper(context)) 

Reset lazy singleton

Get it is awesome! Congrats!

I have to reset (only reset, not unregister) some lazy singletons when the user logout and force to instance a new object. Is there any way to do this?

Thank you!

Using new in readme

In the examples in README.md there is used new keyword few times. It has any deeper meaning or could be removed, as recommended by the official styleguide?

example place: GetIt getIt = new GetIt();

Async Registering, compact model fails

Hi,
if I use:
getIt.registerSingletonAsync<ConfigService>(() async => ConfigService()..init());
the service's registration is not awaited, and it's not working

meanwhile if I use the following, everything is working fine:

getIt.registerSingletonAsync<ConfigService>(() async {
    final configService = ConfigService();
    await configService.init();
    return configService;
  });

Register factories that take parameters

I would like to register factory that takes a parameter and use GetIt to get instance with parameter.

class SomeSource {
  final String someId;
  SomeSource(this.someId);
...
}

getIt.registerFactory((String someId) => SomeSource (someId));

getIt.get<SomeSource>("someId");

Hope it makes sense. If you want more info I can provide.

How to get the existing instance in case object is registered as Factory?

First of all, thank you for this great service locator library. I'm using it in my all 3 projects.

Assuming I have 2 screen A and B. I register a BaseBloc as Factory, thus each time enter these screens, I will get a new instance of BaseBloc.

Screen A has 2 child screens A1 and A2. Instead of passing BaseBloc to A1 and A2, I would like to get use GetIt to get it in A1 and A2 instead. However, since BaseBloc was registered as Factory, in A1 when I have BaseBloc, its data was reset to new instance (not have any data which from A screen).

I wonder if we have any existing solutions for this case? If not, I'm thinking about a new param for GetIt.I<BaseBloc>(returnInstanceIfExisting: true) - which will return existing instance of BaseBloc instead of creating the new one.

How do you think about my idea?

More info:

get_it: ^4.0.0

Flutter version 1.12.13+hotfix.5 at C:\DevTools\flutter
Framework revision 27321ebbad (4 months ago), 2019-12-10 18:15:01 -0800
Engine revision 2994f7e1e6
Dart version 2.7.0

Is relative vs package imports still an issue?

The docs warn

Extremely important if you use GetIt: ALWAYS use the same style to import your project files either as relative paths OR as package which I recommend. DON'T mix them because currently Dart treats types imported in different ways as two different types although both reference the same file.

However I'm wondering if this issue has been solved (and released in possibly Dart 2.1) via
dart-lang/sdk#33076

My tools tend to suggest relative imports at times and I'm curious if I actually need to be diligent about this.

Is it no longer an issue?

Invalid argument (Object of type RegisterModel is not registered inside GetIt.

I have registered my model but it still says "RegisterModel is not registered inside GetIt"

Here is my View class

class RegistrationView extends StatefulWidget {

  @override
  _RegistrationViewState createState() => _RegistrationViewState();
}

class _RegistrationViewState extends State<RegistrationView> {
  
  @override
  Widget build(BuildContext context) {

    return BaseView<RegisterModel>(
        builder: (context, model, child) => Scaffold(
          
          body:Container()
      ),
    );
    // TODO: implement build
  }
}

Here is View Model

class RegisterModel extends BaseModel {
  final AuthenticationService _authenticationService = locator<AuthenticationService>();

  String errorMessage;

  Future<bool> register(String userIdText) async {
    setState(ViewState.Busy);
    var userId = int.tryParse(userIdText);

    // Not a number
    if(userId == null) {
      errorMessage = 'Value entered is not a number';
      setState(ViewState.Idle);
      return false;
    }

    var success = await _authenticationService.register(userId);

    // Handle potential error here too.

    setState(ViewState.Idle);
    return success;
  }
}

Here is locator

GetIt locator = GetIt.instance;

void setupLocator() {

  locator.registerLazySingleton(() => AuthenticationService());
  locator.registerLazySingleton(() => Api());
  locator.registerFactory(() => RegisterModel());

}```
My BaseModel class

class BaseModel extends ChangeNotifier {
ViewState _state = ViewState.Idle;

ViewState get state => _state;

void setState(ViewState viewState) {
_state = viewState;
notifyListeners();
}
}

And Here is issue

> 
is not registered inside GetIt
I/flutter (19507): _RegistrationViewState#1f05d):
I/flutter (19507): Invalid argument (Object of type RegisterModel is not registered inside GetIt.
I/flutter (19507):  Did you forget to pass an instance name?
I/flutter (19507): (Did you accidentally do  GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;)):
I/flutter (19507): RegisterModel
I/flutter (19507):
I/flutter (19507): When the exception was thrown, this was the stack:
I/flutter (19507): #0      GetIt.get 
package:get_it/get_it.dart:76
I/flutter (19507): #1      GetIt.call 
package:get_it/get_it.dart:87
I/flutter (19507): #2      new _BaseViewState 
package:mokoo_dog/…/views/base_view.dart:18
I/flutter (19507): #3      BaseView.createState 
package:mokoo_dog/…/views/base_view.dart:14
I/flutter (19507): #4      new StatefulElement 
package:flutter/…/widgets/framework.dart:3989
I/flutter (19507): #5      StatefulWidget.createElement 
package:flutter/…/widgets/framework.dart:802
I/flutter (19507): #6      Element.inflateWidget 
package:flutter/…/widgets/framework.dart:3082
I/flutter (19507): #7      Element.updateChild 
package:flutter/…/widgets/framework.dart:2887
I/flutter (19507): #8      ComponentElement.performRebuild 
package:flutter/…/widgets/framework.dart:3935
I/flutter (19507): #9      Element.rebuild 
package:flutter/…/widgets/framework.dart:3721
I/flutter (19507): #10     ComponentElement._firstBuild 
package:flutter/…/widgets/framework.dart:3907
I/flutter (19507): #11     StatefulElement._firstBuild 
package:flutter/…/widgets/framework.dart:4053
I/flutter (19507): #12     ComponentElement.mount 
package:flutter/…/widgets/framework.dart:3902
I/flutter (19507): #13     Element.inflateWidget 
package:flutter/…/widgets/framework.dart:3084
I/flutter (19507): #14     Element.updateChild 
package:flutter/…/widgets/framework.dart:2887
I/flutter (19507): #15     SingleChildRenderObjectElement.mount 
package:flutter/…/widgets/framework.dart:5092
I/flutter (19507): #16     Element.inflateWidget 
package:flutter/…/widgets/framework.dart:3084
I/flutter (19507): #17     Element.updateChild 
package:flutter/…/widgets/framework.dart:2887
I/flutter (19507): #18     ComponentElement.performRebuild 
package:flutter/…/widgets/framework.dart:3935
I/flutter (19507): #19     Element.rebuild 
package:flutter/…/widgets/framework.dart:3721
I/flutter (19507): #20     ComponentElement._firstBuild 
package:flutter/…/widgets/framework.dart:3907
I/flutter (19507): #21     ComponentElement.mount 

[web]: Not working in Flutter web release mode

Probelm

Bildschirmfoto 2019-10-04 um 23 01 30

Getting above Error, when running getIt in flutter release mode on my server.

Versions

Flutter: v1.10.12-pre.6
GetIt: ^3.0.1

Flutter Doctor

[✓] Flutter (Channel master, v1.10.12-pre.6, on Mac OS X 10.14.6 18G95, locale de-DE)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.3)
[✓] VS Code (version 1.38.1)
[✓] Connected device (3 available)

• No issues found!

Code

import 'package:get_it/get_it.dart';
import 'dart:js' as js;

GetIt injector;

void main() {
  GetIt.allowMultipleInstances = true;
  injector = new GetIt.asNewInstance();
  injector.registerLazySingleton<UsersAPI>(() => new UsersAPI());
  injector.registerLazySingleton<PushAPI>(() => new PushAPI());
  runApp(MyApp());
}
...

Where to initialize serviceLocator in clean architecture?

I am following clean architecture tutorial from Resocoder https://resocoder.com/flutter-clean-architecture-tdd/ and well that is how I got introduced to Get_it.

I have three questions to ask:

  1. How many service locators should I have in an application?
  2. Should I initialize the ServiceLocator in main?
  3. How do I manage dependencies properly?

In the tutorial it is mentioned that I should have a separate injection_container.dart for each feature. The problem is that some of these features share dependencies due to which if I initialize them in the wrong order, Get_it throws an error. Also I am initializing all this together in main, is there a better way to do this?

If you could point me to a resource where I can read about this further that will be great.

await/async initialization in constructors using get_it

I have a database service (and others) that I want to use with Get_It. But before I can call the methods in the database service, I have to make sure that it's initialized.

So, for a normal service, I would do this:

sl.registerLazySingleton<DatabaseService>(() => DatabaseService());

and then later when I needed it, I would do this:

var db = sl<DatabaseService>();

But because this database service has to be initialized before I can use it, and because it requires an async/await during that process, I have to create an init method like this:

Future<Database> initDb() async {
    // Sqflite.devSetDebugModeOn(true);
    String dbPath = await getDatabasesPath();
    String documentPath = join(dbPath, sqlDatabaseName);

    return await openDatabase(documentPath, version: 1, onOpen: (db) async {
      log.config('database found, opening it...');
    }, onCreate: (Database db, int version) async {
      log.config('database not found, created it...');
      createTableCommands.definitions.forEach((table, command) async {
        await db
            .execute(command)
            .then((_) => log.config('Creating $table table'))
            .catchError((e) => log.shout('Error creating $table table: $e'));
      });
    });
  }

Then I create a getter like this:

 Future<Database> get database async {
    if (_database != null) return _database;
    _database = await initDb();
    return _database;
  }

and everywhere in the code that I want to use it, I do it like this:

Future<void> createTable(String tableName) async {
    final db = await database;
    var command = createTableCommands.definitions[tableName];
    await db
        .execute(command)
        .then((_) => log.config('Creating $tableName table'))
        .catchError((e) => log.shout('Error creating $tableName table: $e'));
  }

And that works.

But it seems really contrived to put a request to the getter at the top of every method that needs the resource. Maybe that's the Dart way, I'm new to this.

Anyway, I saw another approach, which was to make an un-awaited call to the initializer in the constructor and then it's up to the calling code to make sure that the initialization is finished before proceeeding.
I found that here: https://stackoverflow.com/questions/38933801/calling-an-async-method-from-component-constructor-in-dart

class MyComponent{
  MyComponent();

  Future init() async {
    print("init");
  }
}

void main() async {
  var c = new MyComponent();
  await c.init();
  print("done");
}

or another approach here...

class MyComponent{
  Future _doneFuture;

  MyComponent() {
    _doneFuture = _init();
  }

  Future _init() async {
    print("init");
  }

  Future get initializationDone => _doneFuture
}

void main() async {
  var c = new MyComponent();
  await c.initializationDone;
  print("done");
}

I tried using the last one, but what gets registered with Get_It is a Future, so when I reference it, I get a future instead of an instance.

So I found another pattern, here: https://stackoverflow.com/questions/54549235/dart-await-on-constructor

In this one, it seems they want to use a factory method for creating the instance.

class Data {
  String _d;
  Data._();
  static Future<Data> create() async {
    var data = Data._();
    await data._load();
    return data;
  }
  Future<void> _load() async {
    _d = await fn(); 
  }
  String get value => _d;
}

or

class Data {
  String _d;
  Data._(this._d);
  static Future<Data> create() async => Data._(await fn());
  String get value => _d;
}

My question is this: Is there a recommended pattern for handling this kind of situation? I can't be the only one wondering about it. For the moment, I'm going with the getter approach.

when get_it used at showDialog()

showDialog( context: context, barrierDismissible: false, builder: (_) => SettingPage(), );

in dialog , i cant' use
locator<NavigationService>().pop();

should use.
Navigator.of(context).pop();

Error with hot reload

I am getting this error every time my application is hot reloaded

Type HttpService is already registered flutter: 'package:get_it/get_it.dart': Failed assertion: line 53 pos 12: 'allowReassignment || flutter: !_factories.containsKey(T)'

This is my get_it setup
`GetIt sl = new GetIt();

void setupServiceLocator() {
sl.registerSingleton(new HttpService());
sl.registerLazySingleton(() => new TransactionService());
sl.registerLazySingleton(() => new TransactionManagerImplementation());
} `

For solve this I have to make a hot restart, but I don't want to do this every I change my code, can you help me to understand this problem?

Object of type X is not registered inside GetIt

Trying to create objects with get_it, although all the necessary objects are being registered as factories or lazy singletons, the library keeps saying that those objects are not registered.

final sl = GetIt.instance;

Future init() async {

sl.registerFactory(() => MoviesBloc(getMoviesWithPageUsecase: sl()));

sl.registerSingleton(() => GetMoviesWithPageUsecase(sl()));

sl.registerLazySingleton(
() => MoviesRepositoryImpl(
moviesLocalDataSource: sl(),
moviesRemoteDataSource: sl(),
networkInfo: sl()
)
);

sl.registerLazySingleton(
() => MoviesRemoteDataSourceImpl(client: sl())
);
sl.registerLazySingleton(
() => MoviesLocalDataSourceImpl(moviesBox: sl('moviesBox'))
);

sl.registerLazySingleton(
() => NetworkInfoImpl(sl())
);

final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDirectory.path);
final moviesBox = await Hive.openBox('movies');
sl.registerLazySingleton(() => http.Client());
sl.registerLazySingleton(() => DataConnectionChecker());
sl.registerLazySingleton(() => moviesBox,instanceName: 'moviesBox');
}

I call this method inside the main method and when I try to retrieve some object i always get the same error, example:
Invalid argument (Object of type GetMoviesWithPageUsecase is not registered inside GetIt):

add isRegistered method

Some times you want to know if a specific type is registered or not. currently, the only way to know is to get it inside a try-catch.
It would be nice to add some boolean method for that case.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.