Search code examples
flutterflutter-dependenciesdio

Flutter get_it - Register multiple APIs in repo


I am using get_it in My Flutter App. I have registered singletons for network request using dio

Now I want to use multiple base urls in dio requests so I have to create multiple instances for dio.

For that I have to register it once again in get_it. Its giving me an error while registering same types of singletons in get_it repo.

What I have done: I have added two Dio Clients for two different APIs I have add these two lines for registering Dio Clients in GetIt.

First API (Dio Client)

_getIt.registerSingleton<Dio>(DioClient().getDio());

Second API (Dio Client)

_getIt.registerSingleton<Dio>(DioAnotherClient().getDio());

I am Facing this error after doing this:

E/flutter (13845): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument(s): Object/factory with type Dio is already registered inside GetIt.

I am seeking a solution to Use Multiple APIs using GetIt & Dio Package.

Can anyone help me out?


Solution

  • You can have multiple instances of the same class in getIt when you pass an instanceName when registering:

        // First API (Dio Client)
    _getIt.registerSingleton(DioClient().getDio(), instanceName: "first");
    
        // Second API (Dio Client)
    _getIt.registerSingleton(DioAnotherClient().getDio(), instanceName: "second");
    
    final Dio client = _getIt.get(instanceName: "first");