Flutter BLoC GetIt and Dependency Injection

Flutter BLoC GetIt and Dependency Injection

    Flutter BLoC and get_it is a great solution for dependency injection. Make sure you go ahead and install get_it. Once you do it you may create an instance out of it.

    See how we get the instance to GetIt and save in a variable called sl. This instance sl does all the magic. It get the instance of GetIt and call other helper functions. Then we need to register our dependency.

    There are three ways to register dependency with GetIt.

    1. registerFactory
    2. registerSingleton
    3. registerLazySingleton

    In general the next thing we do is to call sl.registerFactory() method. Inside the method, we have to pass the object that should be registered as dependency.

    Let's understand how the basic dependency injection works with GetIt. To inject dependency you need to use one of the above function and mention a class name that needs to injected.

    The simplest way doing it is passing your dependency inside an anonymous function. Let's take a look at the example below

    Here you see that inside registerFactory we return AuthBloc and AuthBloc is a Bloc class for handing events and emitting new states.

    AuthBloc depends on a few other classes like SignIn, SignUp, ForgotPassword and Updateuser class. Each of these classes instances are assigned by calling sl(). 

    sl() would automatically find those instances and assign to AuthBloc.


    Recommended posts

    Recent posts