Introduction to Dependency Injection in Flutter

Manish BasnetManish Basnet
1 min read

In Flutter, Dependency Injection is a technique to supply dependencies to a class or a widget rather than having it create them internally.

In Flutter, widgets or business logic often rely on external objects like:
• A service (e.g., an API client) • A repository (e.g., for data access) • A state manager.

Without DI, you might hardcode these dependencies inside your classes, making it tough to swap them out (e.g., for testing with mocks). DI lets you inject these dependencies from the outside.

Manual Dependency Injection

Step 1: Define a service

Step 2: Create a widget that needs the service

Without DI, you might do this:

Problem: UserWidget creates its own ApiService, so you can’t easily swap it for a mock version during testing.

Step 3: Use Manual DI
Pass the dependency via the constructor.

Step 4: Inject the dependency

In your app’s main widget or wherever you use UserWidget:

Now, UserWidget doesn’t care where ApiService comes from—it’s injected from outside, making it more flexible and testable.

Step 5: Now, for testing, you can create a mock version and inject it.

0
Subscribe to my newsletter

Read articles from Manish Basnet directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manish Basnet
Manish Basnet

I am a developer from Nepal.