Skip to content
Back to search

get_it

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

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/fluttercommunity--get-it/badge.svg)](/listings/fluttercommunity--get-it)

HTML

<a href="/listings/fluttercommunity--get-it"><img src="/api/listings/fluttercommunity--get-it/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Installation

Add to your `pubspec.yaml`:

dependencies:
  get_it: ^8.0.2

Basic Usage

import 'package:get_it/get_it.dart';

// Create a global instance (or use GetIt.instance)
final getIt = GetIt.instance;

// 1. Define your services
class ApiClient {
  Future<void> fetchData() async { /* ... */ }
}

class UserRepository {
  final ApiClient apiClient;
  UserRepository(this.apiClient);
}

// 2. Register them at app startup
void configureDependencies() {
  getIt.registerSingleton<ApiClient>(ApiClient());
  getIt.registerLazySingleton<UserRepository>(
    () => UserRepository(getIt<ApiClient>())
  );
}

// 3. Access from anywhere in your app
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        // No BuildContext passing needed!
        getIt<UserRepository>().apiClient.fetchData();
      },
      child: Text('Fetch Data'),
    );
  }
}

**That's it!** Three simple steps: define, register, access.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 287 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <img align="left" src="https://github.com/flutter-it/get_it/blob/master/get_it.png?raw=true" alt="get_it logo" width="150" style="margin-left: -10px;"/>
  2. <div align="right">
  3. <a href="https://www.buymeacoffee.com/escamoteur"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="28" width="120"/></a>
  4. <br/>
  5. <a href="https://github.com/sponsors/escamoteur"><img src="https://img.shields.io/badge/Sponsor-❤-ff69b4?style=for-the-badge" alt="Sponsor" height="28" width="120"/></a>
  6. </div>
  7. <br clear="both"/>
  8. # get_it <a href="https://codecov.io/gh/flutter-it/get_it"><img align="right" src="https://codecov.io/gh/flutter-it/get_it/branch/master/graph/badge.svg?style=for-the-badge" alt="codecov" width="200"/></a>
  9. > 📚 **[Complete documentation available at flutter-it.dev](https://flutter-it.dev)**
  10. > Check out the comprehensive docs with detailed guides, examples, and best practices!
  11. **A blazing-fast service locator for Dart and Flutter that makes dependency management simple.**
  12. As your app grows, you need a way to access services, models, and business logic from anywhere without tightly coupling your code to widget trees. `get_it` is a simple, type-safe service locator that gives you O(1) access to your objects from anywhere in your app—no `BuildContext` required, no code generation, no magic.
  13. Think of it as a smart container that holds your app's important objects. Register them once at startup, then access them from anywhere. Simple, fast, and testable.
  14. > **flutter_it is a construction set** — get_it works perfectly standalone or combine it with other packages like [watch_it](https://pub.dev/packages/watch_it) (state management), [command_it](https://pub.dev/packages/command_it) (commands), or [listen_it](https://pub.dev/packages/listen_it) (reactive operators). Use what you need, when you need it.
  15. ## Why get_it?
  16. - **⚡ Blazing Fast** — O(1) lookups using Dart's native Maps. No reflection, no slow searches.
  17. - **🎯 Type Safe** — Full compile-time type checking with generics. Errors caught before runtime.
  18. - **🧪 Test Friendly** — Easily swap real implementations for mocks. Reset and reconfigure between tests.
  19. - **🌳 No BuildContext** — Access your objects from anywhere—business logic, utilities, even pure Dart packages.
  20. - **📦 Framework Agnostic** — Works in Flutter, pure Dart, server-side, CLI apps. No Flutter dependencies required.
  21. - **🔧 Zero Boilerplate** — No code generation, no build_runner, no annotations. Just register and use.
  22. [Learn more about the philosophy behind get_it →](https://flutter-it.dev/documentation/get_it/getting_started)
  23. > 💡 **New to service locators?** Read Martin Fowler's classic article on [Inversion of Control Containers and the Dependency Injection pattern](https://martinfowler.com/articles/injection.html) or check out this [detailed blog post on using service locators with Flutter](https://blog.burkharts.net/one-to-find-them-all-how-to-use-service-locators-with-flutter).
  24. ## Quick Start
  25. ### Installation
  26. Add to your `pubspec.yaml`:
  27. ```yaml
  28. dependencies:
  29. get_it: ^8.0.2
  30. ```
  31. ### Basic Usage
  32. ```dart
  33. import 'package:get_it/get_it.dart';
  34. // Create a global instance (or use GetIt.instance)
  35. final getIt = GetIt.instance;
  36. // 1. Define your services
  37. class ApiClient {
  38. Future<void> fetchData() async { /* ... */ }
  39. }
  40. class UserRepository {
  41. final ApiClient apiClient;
  42. UserRepository(this.apiClient);
  43. }
  44. // 2. Register them at app startup
  45. void configureDependencies() {
  46. getIt.registerSingleton<ApiClient>(ApiClient());
  47. getIt.registerLazySingleton<UserRepository>(
  48. () => UserRepository(getIt<ApiClient>())
  49. );
  50. }
  51. // 3. Access from anywhere in your app
  52. class MyHomePage extends StatelessWidget {
  53. @override
  54. Widget build(BuildContext context) {
  55. return ElevatedButton(
  56. onPressed: () {
  57. // No BuildContext passing needed!
  58. getIt<UserRepository>().apiClient.fetchData();
  59. },
  60. child: Text('Fetch Data'),
  61. );
  62. }
  63. }
  64. ```
  65. **That's it!** Three simple steps: define, register, access.
  66. ## Key Features
  67. ### Registration Types
  68. Choose the lifetime that fits your needs:
  69. - **Singleton** — Create once, share everywhere. Perfect for services that maintain state.
  70. [Read more →](https://flutter-it.dev/documentation/get_it/object_registration#singleton)
  71. - **LazySingleton** — Create on first access. Delays initialization until needed.
  72. [Read more →](https://flutter-it.dev/documentation/get_it/object_registration#lazysingleton)
  73. - **Factory** — New instance every time. Great for stateless services or objects with short lifetimes.
  74. [Read more →](https://flutter-it.dev/documentation/get_it/object_registration#factory)
  75. > **Avoid untyped tear-offs as factories.** Registering `getIt.call` (or an untyped `getIt.get` tear-off) as `registerLazySingleton<Iface>(...)` re-enters `get<Iface>()` and used to overflow the stack. For lazy singletons (sync and async) and cached factories GetIt now detects this circular self-resolution and throws a descriptive `StateError`. Plain `registerFactory` factories are not guarded, since a factory that recursively resolves its own type (e.g. to build a tree) is a legitimate pattern. Prefer `() => getIt<Impl>()` or a named function that keeps the concrete type argument.
  76. ### Advanced Features
  77. - **Scopes** — Create hierarchical registration scopes for different app states (login/logout, sessions, feature flags).
  78. [Read more →](https://flutter-it.dev/documentation/get_it/scopes)
  79. - **Async Objects** — Register objects that need async initialization with dependency ordering.
  80. [Read more →](https://flutter-it.dev/documentation/get_it/async_objects)
  81. - **Startup Orchestration** — Easily orchestrate initialization of asynchronous objects during startup.
  82. [Read more →](https://flutter-it.dev/documentation/get_it/async_objects)
  83. - **Named Instances** — Register multiple implementations of the same type with different names.
  84. [Read more →](https://flutter-it.dev/documentation/get_it/advanced#named-instances)
  85. - **Multiple Registrations** — Register multiple implementations and retrieve them all as a collection.
  86. [Read more →](https://flutter-it.dev/documentation/get_it/multiple_registrations)
  87. - **Unregistering** — Remove registrations with `unregister()`, optionally disposing the instance. By default `unregister()` throws if nothing matching is registered (usually a sign that you dispose once too often); set `getIt.skipUnregisterIfNotRegistered = true` to silently ignore a missing registration instead.
  88. [Read more →](https://flutter-it.dev/documentation/get_it/object_registration#unregistering-services)
  89. ### Testing Support
  90. get_it makes testing a breeze:
  91. - **Easy Mocking** — Replace real implementations with mocks using `allowReassignment` or `reset()`
  92. - **Test Isolation** — `reset()` clears all registrations between tests
  93. - **Constructor Injection** — Use optional constructor parameters to inject mocks in tests
  94. ```dart
  95. // In tests
  96. setUp(() {
  97. getIt.registerSingleton<ApiClient>(MockApiClient());
  98. });
  99. tearDown(() async {
  100. await getIt.reset();
  101. });
  102. ```
  103. [Read testing guide →](https://flutter-it.dev/documentation/get_it/testing)
  104. ### DevTools Extension
  105. get_it includes a DevTools extension that lets you visualize and inspect all registered objects in your running app:
  106. - **View all registrations** — See type, instance name, scope, registration mode, async status, ready state, and creation status
  107. - **Instance details** — View the `toString()` output of created instances to inspect their state
  108. - **Manual refresh** — Update the registration list anytime with the refresh button
  109. #### Setup
  110. 1. **Enable debug events** in your app (typically in `main.dart`). This enables the extension to receive automatic updates when registrations change:
  111. ```dart
  112. void main() {
  113. GetIt.instance.debugEventsEnabled = true;
  114. // ... rest of your setup
  115. runApp(MyApp());
  116. }
  117. ```
  118. 2. **Run your app** in debug mode and open DevTools
  119. 3. **Open DevTools in the browser** — The extension currently only works in the browser-based DevTools, not in the IDE-embedded version.
  120. 4. **Enable the extension** — Click the **Extensions** button (puzzle piece icon) in the top right corner of DevTools and enable the `get_it` extension.
  121. 5. **Find the "get_it" tab** — The extension will appear as a new tab in DevTools
  122. For more information on using DevTools extensions, see the [official Flutter DevTools documentation](https://docs.flutter.dev/tools/devtools/extensions).
  123. > **💡 Tip:** Override `toString()` in your registered classes to see meaningful details in the DevTools extension. By default, Dart's `toString()` only shows the type name and instance ID.
  124. ```dart
  125. class UserRepository {
  126. final String userId;
  127. @override
  128. String toString() => 'UserRepository(userId: $userId)';
  129. }
  130. ```
  131. ### Flutter Widget Previews
  132. `get_it` works seamlessly with Flutter's widget previewer. Since previews run in isolation, you need to initialize `get_it` within the preview itself:
  133. ```dart
  134. @Preview()
  135. Widget myPreview() {
  136. if (!getIt.isRegistered<MyService>()) {
  137. getIt.registerSingleton<MyService>(MockService());
  138. }
  139. return const MyWidget();
  140. }
  141. ```
  142. Or use a reusable wrapper for automatic cleanup:
  143. ```dart
  144. @Preview(name: 'My Widget', wrapper: myWrapper)
  145. Widget myPreview() => const MyWidget();
  146. ```
  147. [Read Flutter previews guide →](https://flutter-it.dev/documentation/get_it/flutter_previews)
  148. ## Ecosystem Integration
  149. **get_it works independently** — use it standalone for dependency injection in any Dart or Flutter project.
  150. **Want more?** Combine with other packages from the flutter_it ecosystem:
  151. - **Optional: [watch_it](https://pub.dev/packages/watch_it)** — Reactive state management built on get_it. Watch registered objects and rebuild widgets automatically.
  152. - **Optional: [command_it](https://pub.dev/packages/command_it)** — Command pattern with loading/error states. Integrates seamlessly with get_it services.
  153. - **Optional: [listen_it](https://pub.dev/packages/listen_it)** — ValueListenable operators (map, where, debounce). Use with objects registered in get_it.
  154. **Remember:** flutter_it is a construction set. Each package works independently. Pick what you need, combine as you grow.
  155. [Learn about the ecosystem →](https://flutter-it.dev)
  156. ## AI-Assisted Development
  157. This package ships an [Agent Skill](https://agentskills.io) for AI coding assistants
  158. (Claude Code, Cursor, GitHub Copilot, Codex, Gemini CLI and others) in `skills/get-it-expert/`.
  159. It teaches them the critical rules, common patterns and anti-patterns of get_it.
  160. Install it into your project with the official Dart skills tool:
  161. ```bash
  162. dart run skills@ get
  163. ```
  164. For the ecosystem-wide skills (architecture guidance, feed/data-source patterns, overview)
  165. and the skills of the other flutter_it packages run:
  166. ```bash
  167. dart run skills@ add flutter-it/flutter_it
  168. ```
  169. [Learn more about AI skills →](https://flutter-it.dev/misc/ai_skills)
  170. ## Learn More
  171. ### Documentation
  172. - **[Getting Started](https://flutter-it.dev/documentation/get_it/getting_started)** — Installation, basic concepts, when to use what
  173. - **[Object Registration](https://flutter-it.dev/documentation/get_it/object_registration)** — All registration types, parameters, disposing
  174. - **[Scopes](https://flutter-it.dev/documentation/get_it/scopes)** — Hierarchical scopes, shadowing, scope management
  175. - **[Async Objects](https://flutter-it.dev/documentation/get_it/async_objects)** — Async initialization, dependencies, `allReady()`
  176. - **[Testing](https://flutter-it.dev/documentation/get_it/testing)** — Unit tests, integration tests, mocking strategies
  177. - **[Advanced Topics](https://flutter-it.dev/documentation/get_it/advanced)** — Named instances, multiple GetIt instances, runtime types
  178. - **[FAQ](https://flutter-it.dev/documentation/get_it/faq)** — Common questions and troubleshooting
  179. ### Community & Support
  180. - **[Discord](https://discord.gg/ZHYHYCM38h)** — Get help, share ideas, connect with other developers
  181. - **[GitHub Issues](https://github.com/flutter-it/get_it/issues)** — Report bugs, request features
  182. - **[GitHub Discussions](https://github.com/flutter-it/get_it/discussions)** — Ask questions, share patterns
  183. ### Articles & Resources
  184. - **[One to find them all: How to use Service Locators with Flutter](https://blog.burkharts.net/one-to-find-them-all-how-to-use-service-locators-with-flutter)** — Comprehensive blog post on using get_it
  185. - **[Let's get this party started: Startup orchestration with GetIt](https://blog.burkharts.net/lets-get-this-party-started-startup-orchestration-with-getit)** — Deep dive into async initialization and startup orchestration
  186. - **[Martin Fowler on Service Locator Pattern](https://martinfowler.com/articles/injection.html)** — Classic article on IoC and DI patterns
  187. ## Contributing
  188. Contributions are welcome! Please read the [contributing guidelines](CONTRIBUTING.md) before submitting PRs.
  189. ## License
  190. MIT License - see [LICENSE](LICENSE) file for details.
  191. ## Acknowledgements
  192. Many thanks to [Brian Egan](https://github.com/brianegan) and [Simon Lightfoot](https://github.com/slightfoot) for the insightful discussions on the API design.
  193. ---
  194. **Part of the [flutter_it ecosystem](https://flutter-it.dev)** — Build reactive Flutter apps the easy way. No codegen, no boilerplate, just code.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.