GetIt class abstract
Very simple and easy to use service locator You register your object creation factory or an instance of an object with registerFactory, registerSingleton or registerLazySingleton And retrieve the desired object using get or call your locator as function as its a callable class Additionally GetIt offers asynchronous creation functions as well as functions to synchronize the async initialization of multiple Singletons
Constructors
- GetIt.asNewInstance()
-
If you need more than one instance of GetIt you can use asNewInstance()
You should prefer to use the
instance()
method to access the global instance of GetIt.factory
Properties
- allowReassignment ↔ bool
-
By default it's not allowed to register a type a second time.
If you really need to you can disable the asserts by settingallowReassignment= true
getter/setter pair
- allowRegisterMultipleImplementationsOfoneType ↔ bool
-
getter/setter pair
- currentScopeName → String?
-
Returns the name of the current scope if it has one otherwise null
if you are already on the baseScope it returns 'baseScope'
no setter
- hashCode → int
-
The hash code for this object.
no setterinherited
- onScopeChanged ↔ void Function(bool pushed)?
-
Optional call-back that will get call whenever a change in the current scope happens
This can be very helpful to update the UI in such a case to make sure it uses
the correct Objects after a scope change
The getit_mixin has a matching
rebuiltOnScopeChange
methodgetter/setter pair - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- skipDoubleRegistration ↔ bool
-
By default it's throws error when allowReassignment= false. and trying to register same type
If you really need, you can disable the Asserts / Error by settingskipDoubleRegistration= true
getter/setter pair
Methods
-
allReady(
{Duration? timeout, bool ignorePendingAsyncCreation = false}) → Future< void> -
returns a Future that completes if all asynchronously created Singletons and any
Singleton that had
signalsReady==true
are ready. This can be used inside a FutureBuilder to change the UI as soon as all initialization is done If you pass atimeout
, a WaitingTimeOutException will be thrown if not all Singletons were ready in the given time. The Exception contains details on which Singletons are not ready yet. if allReady should not wait for the completion of async Singletons setignorePendingAsyncCreation==true
-
allReadySync(
[bool ignorePendingAsyncCreation = false]) → bool -
Returns if all async Singletons are ready without waiting
if allReady should not wait for the completion of async Singletons set
ignorePendingAsyncCreation==true
-
call<
T extends Object> ({String? instanceName, dynamic param1, dynamic param2, Type? type}) → T -
Callable class so that you can write
GetIt.instance<MyType>
instead ofGetIt.instance.get<MyType>
-
changeTypeInstanceName<
T extends Object> ({String? instanceName, required String newInstanceName, T? instance}) → void -
In some cases it can be necessary to change the name of a registered instance
This avoids to unregister and reregister the instance which might cause trouble
with disposing functions.
IMPORTANT: This will only change the the first instance that is found while
searching the scopes.
If the new name is already in use in the current scope it will throw a
StateError
instanceName
the current name of the instancenewInstanceName
the new name of the instanceinstance
the instance itself that can be used instead of providing the type and the name. Ifinstance
is null the type and the name have to be provided -
checkLazySingletonInstanceExists<
T extends Object> ({String? instanceName}) → bool -
dropScope(
String scopeName) → Future< void> - Disposes all registered factories and singletons in the provided scope (in the reverse order in which they were registered), then destroys (drops) the scope. If the dropped scope was the last one, the previous scope becomes active again. if you provided dispose functions on registration, they will be called. if you passed a dispose function when you pushed this scope it will be called before the scope is dropped. As dispose functions can be async, you should await this function.
-
enableRegisteringMultipleInstancesOfOneType(
) → void -
Till V7.6.7 GetIt didn't allow to register multiple instances of the same type.
if you want to register multiple instances of the same type you can enable this
and use
getAll()
to retrieve all instances of that parent type -
get<
T extends Object> ({dynamic param1, dynamic param2, String? instanceName, Type? type}) → T -
retrieves or creates an instance of a registered type
T
depending on the registration function used for this type or based on a name. for factories you can pass up to 2 parametersparam1,param2
they have to match the types given at registration with registerFactoryParam()type
if you want to get an instance by a Type object instead of a generic parameter.This should rarely be needed but can be useful if you have a runtime type and want to get an instance -
getAll<
T extends Object> ({dynamic param1, dynamic param2, bool fromAllScopes = false}) → Iterable< T> -
The returned
Iterable
will then contain all registered instances of the requested interfaceT
with or without an instance name. if the registrations are factories they will each be called with the provided parametersparam1,param2
and the results will be returned in the Iterable.fromAllScopes
iftrue
it will return all instances from all scopes otherwise only from the current scope -
getAllAsync<
T extends Object> ({dynamic param1, dynamic param2, bool fromAllScopes = false}) → Future< Iterable< T> > -
The returned
Future<Iterable>
will then contain all registered async registrations of the requested interfaceT
with or without an instance name. if the registrations are factories they will each be called with the provided parametersparam1,param2
and the results will be returned in the Iterable.fromAllScopes
iftrue
it will return all instances from all scopes otherwise only from the current scope -
getAsync<
T extends Object> ({String? instanceName, dynamic param1, dynamic param2, Type? type}) → Future< T> -
Returns a Future of an instance that is created by an async factory or a Singleton that is
not ready with its initialization.
for async factories you can pass up to 2 parameters
param1,param2
they have to match the types given at registration with registerFactoryParamAsync()type
if you want to get an instance by a Type object instead of a generic parameter.This should rarely be needed but can be useful if you have a runtime type and want to get an instance -
hasScope(
String scopeName) → bool -
Tests if the scope by name
scopeName
is registered in GetIt -
isReady<
T extends Object> ({Object? instance, String? instanceName, Duration? timeout, Object? callee}) → Future< void> -
Returns a Future that completes if the instance of a Singleton, defined by Type
T
or by nameinstanceName
or by passing an existinginstance
, is ready If you pass atimeout
, a WaitingTimeOutException will be thrown if the instance is not ready in the given time. The Exception contains details on which Singletons are not ready at that time.callee
optional parameter which makes debugging easier. Passthis
in here. -
isReadySync<
T extends Object> ({Object? instance, String? instanceName}) → bool -
Checks if an async Singleton defined by an
instance
, a typeT
or aninstanceName
is ready without waiting -
isRegistered<
T extends Object> ({Object? instance, String? instanceName}) → bool -
Tests if an
instance
of an object or aTypeT
or a nameinstanceName
is registered inside GetIt -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
popScope(
) → Future< void> - Disposes all factories/Singletons that have been registered in this scope and pops (destroys) the scope so that the previous scope gets active again. if you provided dispose functions on registration, they will be called. if you passed a dispose function when you pushed this scope it will be called before the scope is popped. As dispose functions can be async, you should await this function.
-
popScopesTill(
String name, {bool inclusive = true}) → Future< bool> -
if you have a lot of scopes with names you can pop (see popScope) all
scopes above the scope with
name
including that scope unlessinclusive
= false Scopes are popped in order from the top As dispose functions can be async, you should await this function. If no scope withname
exists, nothing is popped andfalse
is returned -
pushNewScope(
{void init(GetIt getIt)?, String? scopeName, ScopeDisposeFunc? dispose, bool isFinal}) → void -
Creates a new registration scope. If you register types after creating
a new scope they will hide any previous registration of the same type.
Scopes allow you to manage different live times of your Objects.
scopeName
if you name a scope you can pop all scopes above the named one by using the name.dispose
function that will be called when you pop this scope. The scope is still valid while it is executedinit
optional function to register Objects immediately after the new scope is pushed. This ensures that onScopeChanged will be called after their registration ifisFinal
is set to true, you can't register any new objects in this scope after this call. In Other words you have to register the objects for this scope insideinit
if you setisFinal
to true. This is useful if you want to ensure that no new objects are registered in this scope by accident which could lead to race conditions -
pushNewScopeAsync(
{Future< void> init(GetIt getIt)?, String? scopeName, ScopeDisposeFunc? dispose}) → Future<void> -
Creates a new registration scope. If you register types after creating
a new scope they will hide any previous registration of the same type.
Scopes allow you to manage different live times of your Objects.
scopeName
if you name a scope you can pop all scopes above the named one by using the name.dispose
function that will be called when you pop this scope. The scope is still valid while it is executedinit
optional asynchronous function to register Objects immediately after the new scope is pushed. This ensures that onScopeChanged will be called after their registration -
registerCachedFactory<
T extends Object> (FactoryFunc< T> factoryFunc, {String? instanceName}) → void - Like registerFactory but holds a week reference to the last created instance if the instance wasn't garbage collected yet it will return this instance instead of creating a new one
-
registerCachedFactoryAsync<
T extends Object> (FactoryFunc< T> factoryFunc, {String? instanceName}) → void - Like registerFactoryAsync but holds a week reference to the last created instance if the instance wasn't garbage collected yet it will return this instance instead of creating a new one
-
registerCachedFactoryParam<
T extends Object, P1, P2> (FactoryFuncParam< T, P1, P2> factoryFunc, {String? instanceName}) → void - Like registerFactoryParam but holds a week reference to the last created instance if the instance wasn't garbage collected yet, and if the passed parameter haven't changed, it will return this instance instead of creating a new one
-
registerCachedFactoryParamAsync<
T extends Object, P1, P2> (FactoryFuncParam< T, P1, P2> factoryFunc, {String? instanceName}) → void - Like registerFactoryParamAsync but holds a week reference to the last created instance if the instance wasn't garbage collected yet, and if the passed parameter haven't changed, it will return this instance instead of creating a new one
-
registerFactory<
T extends Object> (FactoryFunc< T> factoryFunc, {String? instanceName}) → void -
registers a type so that a new instance will be created on each call of get on that type
T
type to registerfactoryFunc
factory function for this typeinstanceName
if you provide a value here your factory gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. -
registerFactoryAsync<
T extends Object> (FactoryFuncAsync< T> factoryFunc, {String? instanceName}) → void -
registers a type so that a new instance will be created on each call of getAsync on that type
the creation function is executed asynchronously and has to be accessed with getAsync
T
type to registerfactoryFunc
async factory function for this typeinstanceName
if you provide a value here your factory gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. -
registerFactoryParam<
T extends Object, P1, P2> (FactoryFuncParam< T, P1, P2> factoryFunc, {String? instanceName}) → void -
registers a type so that a new instance will be created on each call of get on that type
based on up to two parameters provided to get()
T
type to registerP1
type of param1P2
type of param2 if you use only one parameter pass void herefactoryFunc
factory function for this type that accepts two parametersinstanceName
if you provide a value here your factory gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. -
registerFactoryParamAsync<
T extends Object, P1, P2> (FactoryFuncParamAsync< T, P1?, P2?> factoryFunc, {String? instanceName}) → void -
registers a type so that a new instance will be created on each call of getAsync
on that type based on up to two parameters provided to getAsync()
the creation function is executed asynchronously and has to be accessed with getAsync
T
type to registerP1
type of param1P2
type of param2 if you use only one parameter pass void herefactoryFunc
factory function for this type that accepts two parametersinstanceName
if you provide a value here your factory gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. -
registerLazySingleton<
T extends Object> (FactoryFunc< T> factoryFunc, {String? instanceName, DisposingFunc<T> ? dispose, bool useWeakReference = false}) → void -
registers a type as Singleton by passing a factory function that will be called
on the first call of get on that type
T
type to registerfactoryFunc
factory function for this typeinstanceName
if you provide a value here your factory gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. registerLazySingleton does not influence allReady however you can wait for and be dependent on a LazySingleton. -
registerLazySingletonAsync<
T extends Object> (FactoryFuncAsync< T> factoryFunc, {String? instanceName, DisposingFunc<T> ? dispose, bool useWeakReference = false}) → void -
registers a type as Singleton by passing an async factory function that will be called
on the first call of getAsync on that type
This is a rather esoteric requirement so you should seldom have the need to use it.
This factory function
factoryFunc
isn't called immediately but wait till the first call by getAsync() or isReady() is made To control if an async Singleton has completed itsfactoryFunc
gets aCompleter
passed as parameter that has to be completed to signal that this instance is ready. Therefore you have to ensure that the instance is ready before you use get on it or use getAsync() to wait for the completion. You can wait/check if the instance is ready by using isReady() and isReadySync().instanceName
if you provide a value here your instance gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. registerLazySingletonAsync does not influence allReady however you can wait for and be dependent on a LazySingleton. -
registerSingleton<
T extends Object> (T instance, {String? instanceName, bool? signalsReady, DisposingFunc< T> ? dispose}) → T -
registers a type as Singleton by passing an
instance
of that type that will be returned on each call of get on that typeT
type to register The newly registered instance will also be returned.instanceName
if you provide a value here your instance gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type. IfsignalsReady
is set totrue
it means that the future you can get fromallReady()
cannot complete until this instance was signalled ready by callingsignalsReady(instance)
. -
registerSingletonAsync<
T extends Object> (FactoryFuncAsync< T> factoryFunc, {String? instanceName, Iterable<Type> ? dependsOn, bool? signalsReady, DisposingFunc<T> ? dispose}) → void -
registers a type as Singleton by passing an asynchronous factory function which has to
return the instance that will be returned on each call of get on that type. Therefore
you have to ensure that the instance is ready before you use get on it or use getAsync()
to wait for the completion.
You can wait/check if the instance is ready by using isReady() and isReadySync().
factoryFunc
is executed immediately if there are no dependencies to other Singletons (see below). As soon as it returns, this instance is marked as ready unless you don't setsignalsReady==true
instanceName
if you provide a value here your instance gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type.dependsOn
if this instance depends on other registered Singletons before it can be initialized you can either orchestrate this manually using isReady() or pass a list of the types that the instance depends on here.factoryFunc
won't get executed till this types are ready. IfsignalsReady
is set totrue
it means that the future you can get fromallReady()
cannot complete until this instance was signalled ready by callingsignalsReady(instance)
. In that case no automatic ready signal is made after completion offactoryFunc
-
registerSingletonIfAbsent<
T extends Object> (T factoryFunc(), {String? instanceName, DisposingFunc< T> ? dispose}) → T - ---- With reference counting ----
-
registerSingletonWithDependencies<
T extends Object> (FactoryFunc< T> factoryFunc, {String? instanceName, Iterable<Type> ? dependsOn, bool? signalsReady, DisposingFunc<T> ? dispose}) → void -
registers a type as Singleton by passing a factory function of that type
that will be called when all dependent Singletons are ready
T
type to registerinstanceName
if you provide a value here your instance gets registered with that name instead of a type. This should only be necessary if you need to register more than one instance of one type.dependsOn
if this instance depends on other registered Singletons before it can be initialized you can either orchestrate this manually using isReady() or pass a list of the types that the instance depends on here.factoryFunc
won't get executed till this types are ready.func
is called ifsignalsReady
is set totrue
it means that the future you can get fromallReady()
cannot complete until this instance was signalled ready by callingsignalsReady(instance)
. -
releaseInstance(
Object instance) → void - checks if a registered Singleton has an reference counter > 0 if so it decrements the reference counter and if it reaches 0 it unregisters the Singleton if called on an object that's reference counter was never incremented it will immediately unregister and dispose the object
-
reset(
{bool dispose = true}) → Future< void> -
Clears all registered types in the reverse order in which they were registered.
Handy when writing unit tests or when disposing services that depend on each other.
If you provided dispose function when registering they will be called
dispose
iffalse
it only resets without calling any dispose functions As dispose functions can be async, you should await this function. -
resetLazySingleton<
T extends Object> ({T? instance, String? instanceName, FutureOr disposingFunction(T)?}) → FutureOr -
Clears the instance of a lazy singleton,
being able to call the factory function on the next call
of get on that type again.
you select the lazy Singleton you want to reset by either providing
an
instance
, its registered typeT
or its registration name. if you need to dispose some resources before the reset, you can provide adisposingFunction
. This function overrides the disposing you might have provided when registering. -
resetScope(
{bool dispose = true}) → Future< void> -
Clears all registered types for the current scope in the reverse order of registering them.
If you provided dispose function when registering they will be called
dispose
iffalse
it only resets without calling any dispose functions As dispose functions can be async, you should await this function. -
signalReady(
Object? instance) → void -
Used to manually signal the ready state of a Singleton.
If you want to use this mechanism you have to pass
signalsReady==true
when registering the Singleton. Ifinstance
has a value GetIt will search for the responsible Singleton and completes all futures that might be waited for by isReady If all waiting singletons have signalled ready the future you can get from allReady is automatically completed -
toString(
) → String -
A string representation of this object.
inherited
-
unregister<
T extends Object> ({Object? instance, String? instanceName, FutureOr disposingFunction(T)?, bool ignoreReferenceCount = false}) → FutureOr -
Unregister an
instance
of an object or a factory/singleton by TypeT
or by nameinstanceName
if you need to dispose any resources you can do it usingdisposingFunction
function that provides an instance of your class to be disposed. This function overrides the disposing you might have provided when registering. If you have enabled reference counting when registering, unregister will only unregister and dispose the object if referenceCount is 0ignoreReferenceCount
iftrue
it will ignore the reference count and unregister the object only use this if you know what you are doing
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited