Learn/Architecture Patterns/Dependency Injection

Dependency Injection

Use get_it and injectable for scalable dependency injection

6 min~5 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Lifecycle And Scope Planning
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Dependency Injection

Dependency Injection (DI) is a design pattern where objects receive their dependencies from the outside instead of creating them internally. Without DI, a class would create its own ApiService, DatabaseService, and other dependencies, making it impossible to test in isolation. With DI, you pass those dependencies in through the constructor, and a service locator or container manages the creation and lifetime of all objects. The most popular DI solution in Flutter is get_it, a simple service locator that lets you register and retrieve dependencies from anywhere in your app. For larger projects, the injectable package can auto-generate all registrations using code generation.

dart
1// pubspec.yaml: get_it: ^7.6.0
2import 'package:get_it/get_it.dart';
3
4final getIt = GetIt.instance;
5
6// ── Register dependencies ──
7void setupDependencies() {
8 // Singleton (one instance forever)
9 getIt.registerSingleton<ApiService>(ApiService());
10
11 // Lazy Singleton (created on first use)
12 getIt.registerLazySingleton<DatabaseService>(() => DatabaseService());
13
14 // Factory (new instance every time)
15 getIt.registerFactory<ProductRepository>(
16 () => ProductRepository(getIt<ApiService>(), getIt<DatabaseService>()),
17 );
18
19 // Factory with ChangeNotifier
20 getIt.registerFactory<ProductViewModel>(
21 () => ProductViewModel(getIt<ProductRepository>()),
22 );
23}
24
25// ── Initialize in main ──
26void main() {
27 setupDependencies();
28 runApp(const MyApp());
29}
30
31// ── Use anywhere ──
32final vm = getIt<ProductViewModel>();
33// or
34final api = getIt<ApiService>();
35
36// ── In tests, you can replace implementations ──
37getIt.unregister<ApiService>();
38getIt.registerSingleton<ApiService>(MockApiService());

Without DI vs With DI

💡 Without DI vs With DI

Without DI you must manually construct the entire dependency chain like ProductViewModel(ProductRepository(ApiService(), DatabaseService())). With DI you simply call getIt<ProductViewModel>() and the service locator builds the entire chain for you. DI manages the dependency graph automatically and makes swapping implementations for testing trivial.

Lifecycle And Scope Planning

DI containers are most maintainable when object lifetimes are explicit:

  • Singleton for cross-app services (analytics, auth session manager).
  • Lazy singleton for expensive services needed only in some flows.
  • Factory for short-lived state holders tied to screen lifecycle.
  • Test environment should replace production registrations deterministically.

Correct scope planning prevents stale state, memory leaks, and hidden coupling.

DI Container Checklist

  • All registrations happen in one composition root during startup.
  • Feature modules expose registration methods with clear ownership.
  • Factories are used for stateful classes that should not be shared.
  • Test setup can override any critical service with mocks or fakes.
  • Circular dependency risks are reviewed and eliminated early.

This Lesson In Simple Words

Use get it and injectable for scalable dependency injection. This lesson adds one more building block for creating stable and user-friendly Flutter apps.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.

Deep Understanding Guide

Why this lesson matters

Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Use a simple cycle: understand, implement, test, and explain.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Moving forward without checking whether the current concept is truly clear.
  • Copying code exactly without experimenting with small changes.
  • Skipping edge cases and only testing happy-path behavior.
  • Assuming one pattern works for every scenario without trade-off analysis.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one tiny example from memory after finishing this lesson.
  • Write one paragraph about where this concept fits in a real app.
  • Create one failure scenario and verify your app handles it safely.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What is the difference between registerSingleton and registerFactory?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • const: A compile-time constant that can reduce rebuild work.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Connect this lesson to separation of concerns so your codebase stays maintainable as it grows.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Dependency Injection" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Moving forward without checking whether the current concept is truly clear.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What is the difference between registerSingleton and registerFactory?

Singleton: same instance reused. Factory: new instance created on every getIt<T>() call.

What is the main benefit of Dependency Injection?

DI makes code testable (swap real services with mocks) and modular (change implementations without modifying dependents).

Where should you call setupDependencies()?

Dependencies should be registered once at app startup, before any widget tries to access them.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue