Toor makes service locators compile-time safe and easy to manage

Overview

codecov

🌱 What is Toor

Toor makes service locators compile-time safe and easy to manage.

🚀 Getting Started

Define your dependencies somewhere in the project. It is recommended to make your locators lazily initialized via using the late keyword so that they are created only when used.

final toor = Toor.instance;

late final httpClientSingleton = toor.registerLazySingleton<IHttpClient>(
  DioHttpClientImpl.new,
);

late final authRepositoryFactory = toor.registerFactory<IAuthRepository>(
  () => AuthRepositoryImpl(httpClient: httpClientSingleton()),
);

After that, you can safely access your registered factories or lazy singletons:

void authenticate(String email, String password) {
  authRepositoryFactory().authenticate(email, password);
}

Toor in detail

Types of locators

Toor currently supports two types of objects: factories and lazy singletons.

Factory

Factories are locators that are created on each time you get them.

Use Toor.registerFactory to create factory locators:

final toor = Toor.instance;

late final authRepositoryFactory = toor.registerFactory<IAuthRepository>(
  AuthRepositoryImpl.new,
);

Lazy Singleton

Lazy singletons are locators that are created only on the first call. The object, created at the first call, will be returned every time you get it afterwards.

Use Toor.registerLazySingleton to create lazy singleton locators:

final toor = Toor.instance;

late final credentialManager = toor.registerLazySingleton<ICredentialManager>(
  CredentialManagerImpl.new,
);

Async Factory

Async factories are locators that are asynchronously created each time you get them.

Use Toor.registerFactoryAsync to create async factory locators:

final toor = Toor.instance;

late final dataPersisterFactory = toor.registerFactoryAsync<IDataPersister>(
  () async => SharedPreferencesDataPersister(
    sharedPreferences: await SharedPreferences.getInstance(),
  ),
);

Await the creation of your factory to obtain and use it:

final dataPersister = await dataPersisterFactory();
dataPersister.saveData('big');

Advanced usage

Resetting lazy singletons

You can reset lazy singletons via the reset method. This will delete the current object and create a new one on the next call.

final toor = Toor.instance;

String value = 'Initial';

late final lazySingleton = toor.registerLazySingleton<String>(
  () => value,
);

// Even though we change the `value` variable here,
// `lazySingleton`s value will remain 'Initial'.
value = 'Changed';

print(lazySingleton()); // 'Initial'

// Once we reset `lazySingleton`, it's value will be 'Changed' on the next call.
lazySingleton.reset();

print(lazySingleton()); // 'Changed'

Resetting all lazy singletons

Toor lets you reset all lazy singletons at once via the reset method on its instance. This will call reset on every lazy singleton, registered with it.

final toor = Toor.instance;

String value = 'Initial';

late final lazySingleton = toor.registerLazySingleton<String>(
  () => value,
);

value = 'Changed';

print(lazySingleton()); // 'Initial'

// Once we reset `toor`, all lazy singletons, registered via
// `toor.registerLazySingleton` will be reset.
toor.reset();

print(lazySingleton()); // 'Changed'

Creating new instances of Toor

You may want to create several instances of Toor, independent of each other. The Toor.instance getter will return the default instance but you don't have to use it. You can create new instances of Toor via Toor.newInstance(). You may want to do this in order to reset lazy singletons, related to a single domain (e.g. reset all singletons that hold user data on logout).

final authToor = Toor.newInstance();
final analyticsToor = Toor.newInstance();

late final credentialManager = authToor.registerLazySingleton<ICredentialManager>(
  CredentialManagerImpl.new,
);

late final sessionRecorder = authToor.registerLazySingleton<ISessionRecorder>(
  SessionRecorderImpl(upload: false),
);

void logout() {
  // `credentialManager` will be reset, however `sessionRecorder` won't, since
  // it's registered in `analyticsToor`, not `authToor`.
  authToor.reset();
}

🧪 Testing with Toor

Sometimes, you need different (e.g. mock) objects to be created in tests. There are two ways to achieve that with Toor:

  1. Deciding what to register based on some variables / other toor singletons (e. g. flavor):
final toor = Toor.instance;

late final authManager = toor.registerLazySingleton<IAuthManager>(
  flavor.isTesting ? MockAuthManager() : AuthManagerImpl(),
);
  1. Overriding registered objects via override which is available in toor_test. The override method is annotated with visibleForTesting since it's intended to be used only in tests:
// dependencies.dart
import 'package:toor/toor.dart';

final toor = Toor.instance;

late final authManager = toor.registerLazySingleton<IAuthManager>(
  AuthManagerImpl.new,
);
// app_test.dart
import 'package:toor/toor_test.dart';

void main() {
  setUpAll(() {
    authManager.override(() => MockAuthManager());
  });
}
You might also like...

flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

本仓库不再维护,可移步新仓库 https://github.com/flutter-thrio/flutter_thrio 中文文档 问题集 QQ 群号码:1014085473 The Navigator for iOS, Android, Flutter. Version 0.2.2 requir

Dec 5, 2022

Flutter makes it easy and fast to build beautiful apps for mobile and beyond

Flutter makes it easy and fast to build beautiful apps for mobile and beyond

Flutter is Google's SDK for crafting beautiful, fast user experiences for mobile, web, and desktop from a single codebase. Flutter works with existing

Jan 8, 2023

Nexus is a state management library that makes it easy to create and consume your application's reactive data to the user interface.

Nexus 🚀 Nexus is a state management library that makes it easy to create and consume your application's reactive data to the user interface. With nex

Sep 7, 2022

A Funtioning basic Clock UI APP with extra functionalities such as displaying thecurrent time location being used and checking time for other timezones simultaneosly.

clock_UI A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

Dec 28, 2021

Simple project that consumes the World Time APi and displays the time for the chosen location.

Simple project that consumes the World Time APi and displays the time for the chosen location.

World Time App Simple project that consumes the World Time APi and displays the time for the chosen location. Web Api WorldTime Technologies Flutter A

Jan 20, 2022

A library that makes it easy for you to create your own custom wizard.

A library that makes it easy for you to create your own custom wizard.

Flutter Wizard Author: Jop Middelkamp A library that makes it easy for you to create your custom wizard. You'll have 100% control over the appearance

Dec 2, 2022

🙌🏾 This package makes it easy to use the Mono connect widget in a flutter project

🙌🏾 This package makes it easy to use the Mono connect widget in a flutter project

Flutter Mono ** This is an unofficial SDK for flutter This package makes it easy to use the Mono connect widget in a flutter project. 📸 Screen Shots

Dec 20, 2022

The flutter_ibm_watson makes it easy to integrate IBM Watson

The flutter_ibm_watson makes it easy to integrate IBM Watson

Flutter Ibm Watson Installation Add this to your package's pubspec.yaml file: dependencies: flutter_ibm_watson: ^0.0.1 You can install packages fro

Nov 4, 2022
Home-Service-App - Home Service App Built With Flutter

Home-Service-App Home Service App Sample Images

Justin Roy 2 Sep 4, 2022
Our application, MyArmyPal serves to be an all in one service for our service men.

Our application, MyArmyPal serves to be an all in one service for our service men. It seeks to provide convenience and useful features just one tap away. Its main features include an IPPT Calculator, reservist checklist, customized IPPT training plan according to the user's current fitness level and a canteen order pick up service in all army camps. We are also implementing an anytime Eliss system using computer vision for users to check on their push up form easily.

Poh Wei Pin 3 Jun 17, 2022
Z time ago - A simple Flutter z time ago package used to change date to time ago for english, arabic and kurdish languages

This package is used to get time duration from now and given time for kurdish, a

Zakarya Muhammad 2 May 19, 2022
Safe is an open source mobile platorm to discretely capture incidents with ease, powered by an SMCE written in native Swift and Kotlin.

Safe A powerful tool for personal and community safety. joinsafe.me » Available for iOS & Android ~ Links will be added once a release is available. ~

Safe 10 Oct 26, 2022
🚗 Apple CarPlay for Flutter Apps. Aims to make it safe to use apps made with Flutter in the car by integrating with CarPlay.

CarPlay with Flutter ?? Flutter Apps now on Apple CarPlay! flutter_carplay aims to make it safe to use iPhone apps made with Flutter in the car by int

Oğuzhan Atalay 156 Dec 26, 2022
A platform to make your social media experience more safe

cyber_watch A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if t

Waleed Umar 0 Feb 25, 2022
A web-safe implementation of dart.io.Platforms. Helps avoid the "Unsupported operation: Platform._operatingSystem" runtime error.

Universal Platform - A Web-safe Platform class Currently, if you include the dart.io.Platform anywhere in your code, your app will throw the following

gskinner team 86 Nov 20, 2022
Shared preferences typed - A type-safe wrapper around shared preferences, inspired by ts-localstorage

Typed Shared Preferences A type-safe wrapper around shared_preferences, inspired

Philipp Bauer 0 Jan 31, 2022
Create flutter project with all needed configuration in two minutes (theme, localization, connect to firebase, FCM, local notifications, safe API call, error handling, animation..etc)

Flutter GetX Template Flutter Getx template to make starting project fast and easy . Introduction We all face the same problem when we want to start a

Emad Beltaje 150 Jan 7, 2023
flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

中文文档 英文文档 问题集 原仓库不再维护,代码已经很老了 最近版本更新会很快,主要是增加新特性,涉及到混合栈的稳定性的问题应该不多,可放心升级,发现问题加 QQ 群号码:1014085473,我会尽快解决。 不打算好好看看源码的使用者可以放弃这个库了,因为很多设定是比较死的,而我本人不打算花时间写

null 290 Dec 29, 2022