Bird
Raised Fist0
Fluttermobile~20 mins

Dependency injection (GetIt) in Flutter - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
GetIt Dependency Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flutter widget using GetIt?

Consider this Flutter widget that uses GetIt to get a service instance. What will be displayed on the screen?

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

class CounterService {
  int count = 0;
  void increment() => count++;
}

final getIt = GetIt.instance;

void setup() {
  getIt.registerSingleton<CounterService>(CounterService());
}

class CounterWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = getIt<CounterService>();
    counter.increment();
    return Text('Count: ${counter.count}');
  }
}

void main() {
  setup();
  runApp(MaterialApp(home: Scaffold(body: Center(child: CounterWidget()))));
}
ACount: 1
BRuntime error: Service not found
CCount: 2
DCount: 0
Attempts:
2 left
💡 Hint

Think about when the increment() method is called and how many times the widget builds.

❓ state_output
intermediate
2:00remaining
What is the value of count after multiple widget rebuilds?

Given this Flutter app using GetIt singleton service, what will be the value of count after the button is pressed 3 times?

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

class CounterService {
  int count = 0;
  void increment() => count++;
}

final getIt = GetIt.instance;

void setup() {
  getIt.registerSingleton<CounterService>(CounterService());
}

class CounterApp extends StatefulWidget {
  @override
  State<CounterApp> createState() => _CounterAppState();
}

class _CounterAppState extends State<CounterApp> {
  final counter = getIt<CounterService>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text('Count: ${counter.count}')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            counter.increment();
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

void main() {
  setup();
  runApp(MaterialApp(home: CounterApp()));
}
ACount: 0
BCount: 3
CCount: 1
DCount: 6
Attempts:
2 left
💡 Hint

Each button press calls increment() once and triggers a rebuild.

📝 Syntax
advanced
2:00remaining
Which option correctly registers a lazy singleton with GetIt?

Which code snippet correctly registers a lazy singleton service with GetIt so that the instance is created only when first used?

AgetIt.registerFactory(() => MyService());
BgetIt.registerSingleton(() => MyService());
CgetIt.registerLazySingleton(MyService());
DgetIt.registerLazySingleton(() => MyService());
Attempts:
2 left
💡 Hint

Lazy singleton means the instance is created only when requested first time.

🔧 Debug
advanced
2:00remaining
Why does this GetIt code throw an error at runtime?

Given this code snippet, why does it throw a GetItNotFoundException when trying to get the service?

Flutter
final getIt = GetIt.instance;

class ApiService {}

void main() {
  // Missing registration
  final api = getIt<ApiService>();
}
AThe ApiService was never registered with GetIt before retrieval.
BThe ApiService class is abstract and cannot be instantiated.
CGetIt requires async initialization before use.
DThe GetIt instance was not created with GetIt.instance.
Attempts:
2 left
💡 Hint

Check if the service was registered before calling getIt().

🧠 Conceptual
expert
2:00remaining
What is the main benefit of using GetIt for dependency injection in Flutter?

Choose the best explanation for why developers use GetIt for dependency injection in Flutter apps.

AIt replaces Flutter's widget tree with a service-oriented architecture.
BIt automatically generates UI code based on service definitions.
CIt allows decoupling of object creation from usage, making testing and maintenance easier.
DIt enforces strict compile-time type checking for all dependencies.
Attempts:
2 left
💡 Hint

Think about how dependency injection helps with code structure and testing.

Practice

(1/5)
1. What is the main purpose of using GetIt in a Flutter app?
easy
A. To handle user input events
B. To style widgets with custom themes
C. To manage app navigation between screens
D. To provide shared objects to parts of the app without creating them each time

Solution

  1. Step 1: Understand Dependency Injection

    Dependency injection means giving parts of your app the objects they need without making them create those objects themselves.
  2. Step 2: Role of GetIt

    GetIt is a tool that helps register and provide these shared objects easily in Flutter.
  3. Final Answer:

    To provide shared objects to parts of the app without creating them each time -> Option D
  4. Quick Check:

    Dependency injection = shared objects without recreation [OK]
Hint: GetIt shares objects so you don't recreate them [OK]
Common Mistakes:
  • Confusing GetIt with UI styling tools
  • Thinking GetIt manages navigation
  • Assuming GetIt handles user input
2. Which of the following is the correct way to register a singleton instance with GetIt?
easy
A. GetIt.instance.registerSingleton(() => MyService());
B. GetIt.instance.registerSingleton(MyService());
C. GetIt.instance.registerFactory(() => MyService());
D. GetIt.instance.registerLazySingleton(MyService());

Solution

  1. Step 1: Understand Singleton Registration Syntax

    To register a singleton, you pass an instance directly, not a function.
  2. Step 2: Analyze Options

    GetIt.instance.registerSingleton(MyService()); correctly passes an instance: MyService(). GetIt.instance.registerSingleton(() => MyService()); wrongly passes a function. GetIt.instance.registerFactory(() => MyService()); registers a factory, not a singleton. GetIt.instance.registerLazySingleton(MyService()); passes an instance to lazy singleton incorrectly.
  3. Final Answer:

    GetIt.instance.registerSingleton(MyService()); -> Option B
  4. Quick Check:

    Singleton registration needs instance, not function [OK]
Hint: Singletons get instances, factories get functions [OK]
Common Mistakes:
  • Passing a function instead of an instance for singleton
  • Confusing registerFactory with registerSingleton
  • Using wrong syntax for lazy singleton
3. Given the code below, what will be printed?
final getIt = GetIt.instance;

class Counter {
  int value = 0;
  void increment() => value++;
}

void main() {
  getIt.registerSingleton(Counter());
  final counter1 = getIt<Counter>();
  final counter2 = getIt<Counter>();
  counter1.increment();
  print(counter2.value);
}
medium
A. 1
B. null
C. 0
D. Throws an error

Solution

  1. Step 1: Understand Singleton Behavior

    Registering Counter as a singleton means counter1 and counter2 point to the same instance.
  2. Step 2: Trace the Code Execution

    Calling counter1.increment() increases value from 0 to 1. Since counter2 is the same instance, counter2.value is 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Singleton shares state, so value = 1 [OK]
Hint: Singleton means one shared instance, so changes reflect everywhere [OK]
Common Mistakes:
  • Thinking counter2 is a new instance with value 0
  • Assuming increment does not affect shared instance
  • Expecting null or error without registration
4. What is wrong with this GetIt registration code?
final getIt = GetIt.instance;

void setup() {
  getIt.registerFactory<MyService>(MyService());
}
medium
A. registerFactory expects a function, not an instance
B. registerFactory cannot be called inside a function
C. MyService must be a singleton, not a factory
D. GetIt.instance should not be assigned to a variable

Solution

  1. Step 1: Check registerFactory Syntax

    The registerFactory method expects a function that returns a new instance each time, not an instance itself.
  2. Step 2: Identify the Error

    Passing MyService() directly is an instance, not a function. The correct usage is registerFactory(() => MyService()).
  3. Final Answer:

    registerFactory expects a function, not an instance -> Option A
  4. Quick Check:

    Factories need functions returning new instances [OK]
Hint: Factories need functions, singletons need instances [OK]
Common Mistakes:
  • Passing instance instead of function to registerFactory
  • Thinking registerFactory only works outside functions
  • Confusing singleton and factory registration
5. You want to register a service that should create a new instance every time it is requested. Which GetIt method should you use, and how should you register it?
hard
A. Use registerLazySingleton with a function returning a new instance
B. Use registerSingleton with an instance of the service
C. Use registerFactory with a function returning a new instance
D. Use registerSingleton with a function returning a new instance

Solution

  1. Step 1: Understand the Requirement

    The service must create a new instance every time it is requested, so it should not be a singleton.
  2. Step 2: Choose Correct GetIt Method

    registerFactory registers a function that returns a new instance on each call, matching the requirement.
  3. Step 3: Confirm Registration Syntax

    The correct syntax is registerFactory(() => Service()), passing a function that creates a new instance.
  4. Final Answer:

    Use registerFactory with a function returning a new instance -> Option C
  5. Quick Check:

    New instance each time = registerFactory with function [OK]
Hint: New instance each time? Use registerFactory with a function [OK]
Common Mistakes:
  • Using registerSingleton for new instances
  • Passing instance instead of function to registerFactory
  • Confusing lazy singleton with factory
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard