get_it 3.0.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 99

Flutter Community: get_it

get_it #

Breaking Change with V2.0.0 you no longer can directly create instances of the type GetIt because GetIt is now a singleton please see Getting Started.

IMPORTANT: You have to use Dart2 to use this component #

You can find here a detailed blog post on how to use GetIt

This is a simple Service Locator for Dart and Flutter projects with some additional goodies highly inspired by Splat.

If you are not familiar with the concept of Service Locators, its a way to decouple the interface (abstract base class) from a concrete implementation and at the same time allows to access the concrete implementation from everywhere in your App over the interface. I can only highly recommend to read this classic article by from Martin Fowler Inversion of Control Containers and the Dependency Injection pattern

Accessing an object from anywhere in an App especially can be done by other ways too but:

  • If you use a Singleton you cannot easily switch the implementation to another like a mock version for unit tests
  • IoC containers for Dependency Injections offer a similar functionality but with the cost of slow start-up time and less readability because you don't know where the magically injected object come from. As most IoC libs rely on reflection they cannot be used with Flutter.

Typical usage:

  • Accessing service objects like REST API clients, databases so that they easily can be mocked.
  • Accessing View/AppModels/Managers from Flutter Views
  • Because interface and implementations are decoupled you could also register Flutter Views with different implementations and decide at start-up which one you want to use e.g. depending on screen resolutions

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.

Getting Started #

Before V2.0.0 As Dart supports global (or euphemistic ambient) variables I decided after some discussions with Simon Lightfoot and Brian Egan to use just a simple class (so that you can if you really need even create more than one Locator although I would not advise to do that in most cases).

Since 2.0.0 Although the approach with a global variable worked well, it has its limitations if you want to use GetIt across multiple packages. Therefore now GetIt itself is a singleton and the default way to access an instance of GetIt is to call:

GetIt getIt = GetIt.instance;

//There is also a shortcut (if you don't like it just ignore it):
GetIt getIt = GetIt.I;

Through this any call to instancein any package of a project will get the same instance of GetIt. I still recommend just to assign the instance to a global variable in your project as it is more convenient and doesn't harm (Also it allows you to give your service locator your own name).

GetIt sl = GetIt.instance;

You can use any name you want which makes Brian happy like (sl, backend, services...) ;-)

Before you can access your objects you have to register them within GetIt typically direct in your start-up code.

sl.registerSingleton<AppModel>(AppModelImplementation());
sl.registerLazySingleton<RESTAPI>(() =>RestAPIImplementation());

// if you want to work just with the singleton:
GetIt.instance.registerSingleton<AppModel>(AppModelImplementation());
GetIt.I.registerLazySingleton<RESTAPI>(() =>RestAPIImplementation());

AppModel and RESTAPI are both abstract base classes in this example

To access the registered objects call get<Type>() on your GetItinstance

var myAppModel = sl.get<AppModel>();

Alternatively as GetIt is a callable class depending on the name you choose for your GetItinstance you can use the shorter version:

var myAppModel = sl<AppModel>();

// as Singleton:
var myAppModel = GetIt.instance<AppModel>();
var myAppModel = GetIt.I<AppModel>();

Different ways of registration #

Although I always would recommend using an abstract base class as registration type so that you can vary the implementations you don't have to do this. You can also register concrete types.

GetIt offers different ways how objects are registered that effect the lifetime of this objects.

Factory #

void registerFactory<T>(FactoryFunc<T> func)

You have to pass a factory function func that returns an instance of an implementation of T. Each time you call get<T>() you will get a new instance returned.

Singleton && LazySingleton

void registerSingleton<T>(T instance) 

You have to pass an instance of T or a derived class of T that you will always get returned on a call to get<T>().

As creating this instance can be time consuming at app start-up you can shift the creation to the time the object is the first time requested with:

void registerLazySingleton<T>(FactoryFunc<T> func)

You have to pass a factory function func that returns an instance of an implementation of T. Only the first time you call get<T>() this factory function will be called to create a new instance. After that you will always get the same instance returned.

Overwriting registrations #

If you try to register a type more than once you will get an assertion in debug mode because normally this is not needed and not advised and probably a bug. If you really have to overwrite a registration, then you can by setting the property `allowReassignment==true`` .

Unregistering Singletons or Factories #

If you need to you can also unregister your registered singletons and factories and pass a optional disposingFunction for clean-up.

/// Unregister a factory/ singletons by Type [T] or by name [instanceName]
/// If its a singleton/lazySingleton you can unregister an existing registered object instance 
/// by passing it as [instance]. If a lazysingleton wasn't used before expect 
/// this to throw an `ArgumentError`
/// if you need to dispose any resources you can do it using [disposingFunction] function
/// that provides a instance of your class to be disposed
void unregister<T>({Object instance,String instanceName, void Function(T) disposingFunction})

Resetting GetIt completely #

/// Clears all registered types. Handy when writing unit tests
void reset()

Ready Signal #

Often your registered services need to do initialization work before they can be used from the rest of the app. As this is such a common task and its closely related to registration/initialization I added a handy little feature for it.

GetIt has two properties ready, which is a Stream<void> and readyFuture which is what a surprise a Future<void>. By calling signalReady() on your GetIt instance ready emits an items and readyFutureis signalled. By this you can wait for the end of all initialization with a Stream/FutureBuilder or just listen to the Stream in an initState method.

Automatic ready signal #

In the previous method where you have to call signalReady manually to trigger the ready event. Additionally all your registrations have an internal ready state if you pass signalsReady=true as optional parameter on registration.

The full function definition of signalReady looks like this:

void signalReady([Object instance]) {

By calling it with an registered instance you mark its registration as ready. When all registrations are signalled, ready automatically emits an items and readyFutureis signalled.

Typically the registered service will do that on its own like:

`GetIt.instance.signalReady(this)`

As GetIt is a singleton this can also be done from external packages if they use GetIt.

If you have marked any registrations with signalsReady and you call signalReady() while not all of them are ready, an Exception is thrown. So either you use manual OR automatic signalling. You can not mix them because in most cases this would lead to state errors

Experts region #

Named registration #

DON'T USE THIS IF YOU ARE REALLY KNOW WHAT YOU ARE DOING!!!

This should only be your last resort as you can loose your type safety and lead the concept of a singleton add absurdum. This was added following a request at https://github.com/fluttercommunity/get_it/issues/10

Ok you have been warned. All register functions have an optional named parameter instanceName. If you provide a value here your factory/singleton gets registered with that name instead of a type. Consequently get() has also an optional parameter instanceName to access factories/singletons that were registered by name.

IMPORTANT: Each name for registration can only used once.
Both way of registration are complete separate from each other.

More than one instance of GetIt #

Although I don't recommend it, you can create your own independent instance of GetIt for instance if you don't want to share your locator with some other package or because the physics of your planet demands it :-)

/// To make sure you really know what you are doing
/// you have to first enable this feature:
GetIt.allowMultipleInstances=true;
GetIt myOwnInstance = GetIt.asNewInstance();

This new instance does not share any registrations with the singleton instance

Acknowledgements #

Many thanks to the insightful discussions on the API with Brian Egan and Simon Lightfoot

[3.0.2] - 23.10.2019

  • Bugfix when using named instances

[3.0.1] - 24.09.2019

[3.0.0+1] - 07.09.2019

  • Small fix to make the analyser happy

[3.0.0] - 07.09.2019

  • Overhauled the signalling API because the way it was was not optimal. Now you can either signal globally or by passing the instance of the registered object that shall signal. This way it's ensured that you have to have access to the instance to signal, typically from within the instance with a GetIt.instance.signalReady(this) individual signalling from other places but the instance itself is probably an error.
  • Unregister of singletons /lazysingletons now possible also over a registered instance.
  • Most asserts have bin replaced with throwing Errorobjects.
  • The example now shows the ready signalling.

[2.1.0] - 26.08.2019

  • Added handy ready signal to make start-up logic a bit easier
  • Unregister of Objects now possible with optional disposing function

[2.0.3] - 26.08.2019

  • Small fix

[2.0.2] - 19.08.2019

  • Small fix

[2.0.1] - 19.08.2019

  • Small fix

[2.0.0] - 18.08.2019

  • Breaking Change with V2.0.0 you no longer can directly create instances of the type GetIt because GetIt is now a singleton please see README

[1.1.0] - 18.08.2019

  • added named registration

[1.0.3+2] - 26.06.2019

  • updated logo in readme

[1.0.3+1] - 22.05.2019

  • updated authors

[1.0.3] - 01.03.2019

  • Small fix so that intellisense works now if you use the short calling form without using .get()

[1.0.2] - 22.06.2018

[1.0.1] - 20.06.2018

  • Added reset()method

[1.0.0] - 22.05.2018

  • Initial release

example/README.md

get_it_example #

A new Flutter project.

Getting Started #

For help getting started with Flutter, view our online documentation.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  get_it: ^3.0.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:get_it/get_it.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
99
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
99
Learn more about scoring.

We analyzed this package on Oct 23, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:get_it/get_it.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev<3.0.0
meta ^1.1.0 1.1.7
Dev dependencies
test any