0
0
Fluttermobile~5 mins

Dependency injection (GetIt) in Flutter

Choose your learning style9 modes available
Introduction

Dependency injection helps you organize your app by giving parts what they need without making them find it themselves. GetIt is a simple tool to do this in Flutter.

When you want to share a single object, like a service, across many parts of your app.
When you want to make your code easier to test by swapping real objects with fake ones.
When you want to avoid creating the same object multiple times.
When you want to keep your widgets clean and not worry about how to create dependencies.
When you want a simple way to manage app-wide objects without complex setup.
Syntax
Flutter
final getIt = GetIt.instance;

// Register a singleton
getIt.registerSingleton<MyService>(MyService());

// Access the registered service
var service = getIt<MyService>();

Use registerSingleton to create one shared instance.

Use getIt() to get the instance anywhere in your app.

Examples
This example shows how to register and get a simple service that counts.
Flutter
final getIt = GetIt.instance;

// Register a singleton service
getIt.registerSingleton<CounterService>(CounterService());

// Later, get the service
var counter = getIt<CounterService>();
Using registerFactory creates a new object every time you ask for it.
Flutter
final getIt = GetIt.instance;

// Register a factory to create a new instance each time
getIt.registerFactory<Logger>(() => Logger());

// Get a new Logger instance
var logger1 = getIt<Logger>();
var logger2 = getIt<Logger>();
Sample App

This Flutter app uses GetIt to share a CounterService across widgets. The count updates when you press the button.

Flutter
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';

// Simple service that holds a count
class CounterService {
  int count = 0;

  void increment() {
    count++;
  }
}

final getIt = GetIt.instance;

void main() {
  // Register the CounterService as a singleton
  getIt.registerSingleton<CounterService>(CounterService());

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CounterScreen(),
    );
  }
}

class CounterScreen extends StatefulWidget {
  @override
  State<CounterScreen> createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  // Get the service instance
  final counterService = getIt<CounterService>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('GetIt Dependency Injection')),
      body: Center(
        child: Text('Count: ${counterService.count}', style: TextStyle(fontSize: 24)),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            counterService.increment();
          });
        },
        child: Icon(Icons.add),
        tooltip: 'Increment count',
      ),
    );
  }
}
OutputSuccess
Important Notes

Remember to register your services before running the app.

Singletons keep the same instance, factories create new ones each time.

GetIt helps keep your widgets simple and focused on UI.

Summary

Dependency injection gives parts of your app what they need without making them create it.

GetIt is an easy tool to register and get shared objects in Flutter.

Use singletons for shared objects and factories for new instances.