Search⌘ K

Dependency Injection

Explore how to use dependency injection in Flutter applications to provide and share dependencies like controllers efficiently. This lesson guides you through implementing dependency injection with the Get package to manage state, update UI reactively, and handle tasks such as adding, deleting, and updating items in a to-do app. Understand how this technique helps isolate object creation and simplifies state management in large Flutter apps.

Introduction

Dependency injection (DI) supplies classes/objects in our app with other objects on which they depend. Instead of instantiating the dependent objects, a dependency injector injects the dependent objects into our class. This method becomes essential if we are building a large application with nested widgets, as the use and creation of an object are isolated.

In this lesson, we’ll work on the simple app below to add dependency injection. We will use the Get package (also known as GetX) as our dependency manager or a service locator. One of the advantages of using the get package is that it allows us to share dependencies around the application without depending on Flutter’s BuildContext object.

import 'package:flutter/material.dart';

import 'presentation/my_app.dart';

void main() {
  runApp(const MyApp());
}
Dependency injection with GetX—initial code

Installing the Get package

We’ll first need to install the Get package. Go to the pubspec.yaml file at the root of your application and locate the to-do item labeled # TODO-1: Add the get package (line 11). Replace it with the following line of code under the dependencies section:

YAML
get: ^4.6.5

Declaring the controller

Locate the ...