Mastering
Dependency Injection
in Flutter
A Step-by-Step Guide
@Rida Syed
Concept of
Dependency Injection
The main idea of Dependency Injection is to
provide dependencies externally instead of
creating them within a class. This way, the
class only focuses on its main functionality,
and the dependencies are injected from an
external source.
@Rida Syed
Implementing Dependency
Injection in Flutter
In Flutter, you can implement DI using
several techniques and packages. Some
popular packages are:
Provider
GetIt
Riverpod
@Rida Syed
Example Using
Provider Flutter
Provider is used for both state management
and dependency injection in Flutter. It’s a
simple and effective way to manage
dependencies.
Step 1: Add Dependencies in pubspec.yaml
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0
@Rida Syed
Example Using
Provider Flutter
Step 2: Define a Service or Dependency
class ApiService {
String fetchData() {
return "Data from ApiService";
}
}
@Rida Syed
Example Using
Provider Flutter
Step 3: Provide the Dependency Using Provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
Provider<ApiService>(create: (_) => ApiService()),
],
child: MyApp(),
),
);
}
@Rida Syed
Example Using
Provider Flutter
Step 4: Access the Dependency in Widgets
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final apiService = Provider.of<ApiService>(context, listen:
false);
return Scaffold(
appBar: AppBar(title: Text('Dependency Injection
Example')),
body: Center(
child: Text(apiService.fetchData()),
),
);
}
}
@Rida Syed
Benefits of
Dependency Injection
Loose Coupling: Classes don’t create their
dependencies, making it easy to change or replace
dependencies without affecting the classes that use
them.
Improved Testability: Dependencies can be easily
mocked or stubbed during testing, making unit testing
straightforward.
Better Organization: Dependencies are managed
centrally, improving code organization and readability.
Code Reusability: Services and dependencies can be
reused across different parts of the application without
redundancy.
@Rida Syed
Benefits of
Dependency Injection
Loose Coupling: Classes don’t create their
dependencies, making it easy to change or replace
dependencies without affecting the classes that use
them.
Improved Testability: Dependencies can be easily
mocked or stubbed during testing, making unit testing
straightforward.
Better Organization: Dependencies are managed
centrally, improving code organization and readability.
Code Reusability: Services and dependencies can be
reused across different parts of the application without
redundancy.
@Rida Syed
FOLLOW
For more useful content
@Rida Syed