패키지, 저장소 및 앱 카테고리 검색

패키지 상세v3.0.0

injectable

Injectable은 get_it용 편리한 코드 생성기입니다. Angular DI, Guice DI, inject.dart에서 영감을 받았습니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
46만
좋아요
1.5천
Pub 점수
160

패키지 설치

flutter pub add injectable

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Injectable은 get_it 서비스 로케이터를 사용하여 Flutter의 종속성 주입을 단순화하는 코드 생성 도구입니다. Angular, Guice, inject.dart에서 영감을 받아 어노테이션을 통해 깔끔하고 타입 안전하며 유지보수 가능한 종속성 관리를 가능하게 합니다. 개발자는 간단한 데코레이터로 종속성을 정의하고, 생성기가 자동으로 필요한 등록 코드를 생성합니다. 이는 반복 코드를 줄이고, 특히 대규모 애플리케이션에서 코드 조직을 향상시킵니다.

사용 사례

  • 대규모 플러터 애플리케이션
  • 모듈러 앱 아키텍처
  • 모의 종속성으로 테스트하기
  • 다중 환경 간 종속성 관리
  • 서비스 및 리포지토리 주입 간소화

주요 기능

  • 코드 생성을 통한 자동 종속성 등록
  • 타입 안전한 종속성 주입
  • 지연 및 싱글턴 인스턴스 지원
  • get_it 서비스 로케이터와의 통합
  • 단순한 모킹을 통한 단위 테스트

적합한 대상

  • 구조적인 종속성 관리를 원하는 개발자
  • 복잡한 Flutter 프로젝트를 진행 중인 팀
  • 테스트 가능성과 유지보수성을 요구하는 프로젝트

고려 사항

  • 코드 생성 및 build_runner에 대한 이해가 필요합니다
  • 빌드 구성에 대한 추가 설정 단계
  • 빌드 시간을 약간 증가시킬 수 있습니다
  • 기본 서비스 로케이터로 get_it에 의존

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Injectable

MIT License stars pub version Buy Me A Coffee


Installation

dependencies:
  # add injectable to your dependencies  
  injectable:
  # add get_it  
  get_it:

dev_dependencies:
  # add the generator to your dev_dependencies  
  injectable_generator:
  # add build runner if not already added  
  build_runner:  

LeanBuilder support (Experimental) ⚡

injectable_generator (2.12.0+) now supports LeanBuilder for super-fast incremental builds.

To use lean_builder instead of build_runner, simply add it to your dev_dependencies:

dev_dependencies:
  injectable_generator: <latest-version>
  lean_builder: <latest-version>

and then run the builder using:

For one-time build:

dart run lean_builder build

For watching files and rebuilding on changes:

dart run lean_builder watch

To disable injectable_generator from using build_runner, you can add the following to your build.yaml file:

targets:
  $default:
    builders:
      injectable_generator:injectable_builder:
        enabled: false
      injectable_generator:injectable_config_builder:
        enabled: false

Setup


  1. Create a new dart file and define a global var for your GetIt instance.
  2. Define a top-level function (lets call it configureDependencies) then annotate it with @injectableInit.
  3. Import the Generated dart file created later on in the code. This will follow the name of the file with the @InjectableInit annotated func, eg file_name.config.dart.
  4. Call the Generated extension func getIt.init(), or your custom initializer name inside your configure func.

Note: This example is for version 2+

import '<FILE_NAME>.config.dart';
	
final getIt = GetIt.instance;  
  
@InjectableInit(  
  initializerName: 'init', // default  
  preferRelativeImports: true, // default  
  asExtension: true, // default  
  generateAccessors: false, // default  
)  
void configureDependencies() => getIt.init();  

Note: you can tell injectable what directories to generate for using the generateForDir property inside of @injectableInit.
The following example will only process files inside of the test folder.

import '<FILE_NAME>.config.dart';
	
@InjectableInit(generateForDir: ['test'])  
void configureDependencies() => getIt.init();  
  1. Call configureDependencies() in your main func before running the App.
void main() {  
 configureDependencies();  
 runApp(MyApp());  
}  

Registering factories


All you have to do now is annotate your injectable classes with @injectable and let the generator do the work.

@injectable  
class ServiceA {}  
  
@injectable  
class ServiceB {  
    ServiceB(ServiceA serviceA);  
}  
  
Cached Factories

To register cached factories pass true to the cache property inside of the @Injectable annotation.


@Injectable(cache: true)
class ServiceA {}
  

to read more about cached factories check the GetIt docs

Run the generator

Use the [watch] flag to watch the files' system for edits and rebuild as necessary.

flutter packages pub run build_runner watch  

if you want the generator to run one time and exits use

flutter packages pub run build_runner build  
Inside of the generated file

Injectable will generate the needed register functions for you.

import 'package:get_it/get_it.dart' as _i1;

extension GetItInjectableX on _i1.GetIt {
  /// initializes the registration of main-scope dependencies inside of [GetIt]  
  Future<_i1.GetIt> init({
    String? environment,
    _i2.EnvironmentFilter? environmentFilter,
  }) async {
    final gh = _i2.GetItHelper(
      this,
      environment,
      environmentFilter,
    );
    gh.factory<ServiceA>(() => ServiceA());
    gh.factory<ServiceB>(ServiceA(getIt<ServiceA>()));
    return this;
  }
}  

Generating Accessor Methods


By default, dependencies are accessed using getIt.get<Type>(). However, you can enable the generateAccessors property in @InjectableInit to generate convenient accessor methods that provide a cleaner, more concise API.

Enabling Accessor Generation

Simply set generateAccessors: true in your @InjectableInit annotation:

@InjectableInit(generateAccessors: true)
void configureDependencies() => getIt.init();
Simple Type Access

Without generateAccessors, you use the standard GetIt syntax:

// Without generateAccessors
var userService = getIt.get<UserService>();
var database = getIt.get<Database>();

With generateAccessors: true, the generator creates convenient getter methods:

// With generateAccessors: true
var userService = getIt.userService;
var database = getIt.database;

The generator automatically converts type names to camelCase for the accessor names (UserService → userService).

Parameterized Dependencies

For dependencies that accept parameters (factory parameters or instance names), accessor methods are generated with those same parameters:

Without generateAccessors:

@injectable
class UserRepository {
  UserRepository(@factoryParam String userId);
}

// Usage
var repository = getIt.get<UserRepository>(param1: 'user123');
var cachedDb = getIt.get<Database>(instanceName: 'primary');

With generateAccessors: true:

// Generated accessors:
// UserRepository userRepository({required String userId}) =>
//   get<UserRepository>(param1: userId);
// Database database({String? instanceName}) =>
//   get<Database>(instanceName: instanceName);

// Usage
var repository = getIt.userRepository(userId: 'user123');
var cachedDb = getIt.database(instanceName: 'primary');
Generated Extension

Internally, generateAccessors generates accessor methods which are added to the generated GetItInjectableX extension:

extension GetItInjectableX on GetIt {
  /// init method omitted for readability

  UserService get userService => get<UserService>();
  
  Database database({String? instanceName}) =>
    get<Database>(instanceName: instanceName);
  
  UserRepository userRepository({required String userId}) =>
    get<UserRepository>(param1: userId);
}

This provides IDE autocomplete support and type safety while keeping your code clean and readable.

Registering singletons


Use @singleton or @lazySingleton to annotate your singleton classes. Alternatively use the constructor version to pass signalsReady to getIt.registerSingleton(signalsReady) @Singleton(signalsReady: true) >> getIt.registerSingleton(Model(), signalsReady: true) @LazySingleton() >> getIt.registerLazySingleton(() => Model())

@singleton // or @lazySingleton  
class ApiProvider {}  

Disposing of singletons

GetIt provides a way to dispose singleton and lazySingleton instances by passing a dispose callback to the register function. Injectable works in the static realm, which means it's not possible to pass instance functions to your annotation; luckily injectable provides two simple ways to handle instance disposal.

1- Annotating an instance method inside of your singleton class with @disposeMethod.

@singleton // or lazySingleton  
class DataSource {

  @disposeMethod
  void dispose(){
    // logic to dispose instance  
  }
}  

2- Passing a reference to a dispose function to Singleton() or LazySingleton() annotations.

@Singleton(dispose: disposeDataSource)
class DataSource {

  void dispose() {
    // logic to dispose instance  
  }
}
/// dispose function signature must match Function(T instance)  
FutureOr disposeDataSource(DataSource instance){
  instance.dispose();
}

Multiple Registrations

GetIt supports registering multiple instances of the same type without names. To enable this feature, set allowMultipleRegistrations: true in @InjectableInit:

@InjectableInit(
  allowMultipleRegistrations: true,
)
void configureDependencies() => getIt.init();

This generates a call to getIt.enableRegisteringMultipleInstancesOfOneType() at the start of the init function, allowing you to register multiple implementations as the same type:

@Injectable(as: Plugin)
class PluginA implements Plugin {}

@Injectable(as: Plugin)
class PluginB implements Plugin {}

Without allowMultipleRegistrations, the above would fail with a "type already registered" error since both classes register as Plugin.

You can then retrieve all instances using getIt.getAll<Plugin>(). Note that getIt<Plugin>() returns only the first registered instance.

Note: Once enabled, this setting applies globally and cannot be disabled. See GetIt documentation for more details.

FactoryMethod and PostConstruct Annotations

As the name suggests @FactoryMethod annotation is used to tell injectable which method to use to create the dependency, and that includes named constructors, factory constructs and static create methods.

@injectable
class MyRepository {
  @factoryMethod
  MyRepository.from(Service s);
}  

The constructor named "from" will be used when building MyRepository.

factory<MyRepository>(MyRepository.from(getIt<Service>()))  

or annotate static create functions or factories inside of abstract classes with @factoryMethod.

@injectable
abstract class Service {
  @factoryMethod
  static ServiceImpl2 create(ApiClient client) => ServiceImpl2(client);

  @factoryMethod
  factory Service.from() => ServiceImpl();
}  

on the other hand @PostConstruct annotation is used to initialize the constructed dependency synchronously or asynchronously and that only includes public member methods.

@Injectable()
class SomeController  {
  SomeController(Service service);

  @PostConstruct()
  void init() {
    //...init code  
  }

}  

now both of these annotations take an optional bool flag preResolve. If the create or initialize methods return a future and preResolve is true, the future will be pre-resolved ( awaited ) before the dependency is registered inside of GetIt, otherwise it's registered as an async dependency.

Registering asynchronous injectables

Requires GetIt >= 4.0.0 if we are to make our instance creation async we're gonna need a static initializer method since constructors can not be asynchronous.

class ApiClient {
  static Future<ApiClient> create(Deps ...) async {
  ....
  return apiClient;
  }
}  

Now simply annotate your class with @injectable and tell injectable to use that static initializer method as a factory method using the @factoryMethod annotation

@injectable // or lazy/singleton  
class ApiClient {
  @factoryMethod
  static Future<ApiClient> create(Deps ...) async {
  ....
  return apiClient;
  }
}  

injectable will automatically register it as an asynchronous factory because the return type is a Future.

Generated Code:
factoryAsync<ApiClient>(() => ApiClient.create());  
Using a register module (for third party dependencies)

just wrap your instance with a future, and you're good to go.

@module
abstract class RegisterModule {
  Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}  

Don't forget to call getAsync<T>() instead of get<T>() when resolving an async injectable.

Pre-Resolving futures

if you want to pre-await the future and register its resolved value, annotate your async dependencies with @preResolve.

@module
abstract class RegisterModule {
  @preResolve
  Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
}  

It also works with @factoryMethod and @postConstruct annotations.

@Injectable()
class AsyncService  {
  AsyncService(Service service);

  // @preResolve -> this works as well  
  @FactoryMethod(preResolve: true)
  static Future<AsyncService> create(@factoryParam String? param) =>
      Future.value(AsyncService(Service.from(param));
      }  
@Injectable()
class SomeController  {
  SomeController(Service service);

  // @preResolve -> this works as well  
  @PostConstruct(preResolve: true)
  Future<AsyncService> init(@factoryParam String? param) =>
      Future.value(SomeController(Service.from(param));
      }  
Generated Code:
import 'package:get_it/get_it.dart' as _i1;

extension GetItInjectableX on _i1.GetIt {
  /// initializes the registration of main-scope dependencies inside of [GetIt]  
  Future<_i1.GetIt> init({
    String? environment,
    _i2.EnvironmentFilter? environmentFilter,
  }) async {
    final gh = _i2.GetItHelper(
      this,
      environment,
      environmentFilter,
    );
    final registerModule = _$RegisterModule();
    final sharedPreferences = await registerModule.prefs;
    gh.factory<SharedPreferences>(() => sharedPreferences);
    return this;
  }
}  

as you can see this will make your init func async so be sure to await for it.

Passing Parameters to factories


Requires GetIt >= 4.0.0

If you're working with a class you own simply annotate your changing constructor param with @factoryParam, you can have up to two parameters max!

@injectable
class BackendService {
  BackendService(@factoryParam String url);
}  
Generated Code:
factoryParam<BackendService, String, dynamic>(
(url, _) => BackendService(url),
);  
Using a register module (for third party dependencies)

if you declare a module member as a method instead of a simple accessor, injectable will treat it as a factory method, meaning it will inject its parameters as it would with a regular constructor.

This is similar to how if you annotate an injected param with @factoryParam injectable will treat it as a factory param.

@module
abstract class RegisterModule {
  BackendService getService(ApiClient client, @factoryParam String url) => BackendService(client, url);
}  
Generated Code:
factoryParam<BackendService, String, dynamic>(
(url, _) => registerModule.getService(g<ApiClient>(), url));  

Binding abstract classes to implementations

--- Use the 'as' Property inside of Injectable(as:..) to pass an abstract type that's implemented by the registered dependency

@Injectable(as: Service)
class ServiceImpl implements Service {}

// or  
@Singleton(as: Service)
class ServiceImpl implements Service {}

// or  
@LazySingleton(as: Service)
class ServiceImpl implements Service {}

Generated Code:
factory<Service>(() => ServiceImpl())  
Binding an abstract class to multiple implementations

Since we can't use type binding to register more than one implementation, we have to use names (tags) to register our instances or register under different environment. (we will get to that later)

@Named("impl1")
@Injectable(as: Service)
class ServiceImpl implements Service {}

@Named("impl2")
@Injectable(as: Service)
class ServiceImp2 implements Service {}  

Next annotate the injected instance with @Named() right in the constructor and pass in the name of the desired implementation.

@injectable
class MyRepo {
  final Service service;
  MyRepo(@Named('impl1') this.service)
}  
Generated Code:
factory<Service>(() => ServiceImpl1(), instanceName: 'impl1')
factory<Service>(() => ServiceImpl2(), instanceName: 'impl2')

factory<MyRepo>(() => MyRepo(getIt('impl1'))  
Auto Tagging

Use the lower cased @named annotation to automatically assign the implementation class name to the instance name. Then use @Named.from(Type) annotation to extract the name from the type.

@named
@Injectable(as: Service)
class ServiceImpl1 implements Service {}

@injectable
class MyRepo {
  final Service service;
  MyRepo(@Named.from(ServiceImpl1) this.service)
}  
Generated Code:
factory<Service>(() => ServiceImpl1(), instanceName: 'ServiceImpl1')
factory<MyRepo>(() => MyRepo(getIt('ServiceImpl1'))  

Register under different environments


it is possible to register different dependencies for different environments by using @Environment('name') annotation. in the below example ServiceA is now only registered if we pass the environment name to $init(environment: 'dev').

@Environment("dev")
@injectable
class ServiceA {}  

you could also create your own environment annotations by assigning the const constructor Environment("") to a global const var.

const dev = Environment('dev');
// then just use it to annotate your classes  
@dev
@injectable
class ServiceA {}  

You can assign multiple environment names to the same class.

@test
@dev
@injectable
class ServiceA {}  

Alternatively use the env property in injectable and subs to assign environment names to your dependencies.

@Injectable(as: Service, env: [Environment.dev, Environment.test])
class RealServiceImpl implements Service {}  

Now passing your environment to init function will create a simple environment filter that will only validate dependencies that have no environments or one of their environments matches the given environment.
Alternatively, you can pass your own EnvironmentFilter to decide what dependencies to register based on their environment keys, or use one of the shipped ones:

  • NoEnvOrContainsAll
  • NoEnvOrContainsAny
  • SimpleEnvironmentFilter

Registering third party types


To Register third party types, create an abstract class and annotate it with @module then add your third party types as property accessors or methods as follows:

@module
abstract class RegisterModule {
  @singleton
  ThirdPartyType get thirdPartyType;

  @prod
  @Injectable(as: ThirdPartyAbstract)
  ThirdPartyImpl get thirdPartyType;
}  
Providing custom initializers

In some cases you'd need to register instances that are asynchronous or singleton instances or just have a custom initializer and that's a bit hard for injectable to figure out on its own, so you need to tell injectable how to initialize them:

@module
abstract class RegisterModule {
  // You can register named preemptive types like follows  
  @Named("BaseUrl")
  String get baseUrl => 'My base url';

  // url here will be injected  
  @lazySingleton
  Dio dio(@Named('BaseUrl') String url) => Dio(BaseOptions(baseUrl: url));

  // same thing works for instances that's gotten asynchronous.  
  // all you need to do is wrap your instance with a future and tell injectable how  
  // to initialize it  
  @preResolve // if you need to pre resolve the value  
  Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
// Also, make sure you await for your configure function before running the App.  
}  

if you're facing even a weirder scenario you can always register them manually in the configure function.

Auto registering


Instead of annotating every single injectable class you write, it is possible to use a Convention Based Configuration to auto register your injectable classes, especially if you follow a concise naming convention.

For example, you can tell the generator to auto-register any class that ends with Service, Repository or Bloc
using a simple regex pattern
class_name_pattern: 'Service$|Repository$|Bloc$'
To use auto-register create a file with the name build.yaml in the same directory as pubspec.yaml and add

targets:
  $default:
    builders:
      injectable_generator:injectable_builder:
        options:
          auto_register: true
          # auto registers any class with a name matches the given pattern  
          class_name_pattern:
            "Service$|Repository$|Bloc$"
            # auto registers any class inside a file with a  
          # name matches the given pattern  
          file_name_pattern: "_service$|_repository$|_bloc$"  

Manual order

By default injectable tries to re-order dependencies based on their dependents, meaning if A depends on B, B will be registered first.

You can manually decide the order of a specific dependency by giving it a negative number to register it before everything else or a positive number to register it after everything else.

Note All dependencies have order of 0 by default.
You specify the custom order by using annotation @Order(number) or using the property order inside of injectable and subs

// @Order(-1) this works too  
@Injectable(order: -1)
class Service{}  

Using Scopes

GetIt v5.0 introduced scopes support, which allows registration of related dependencies in a different scope, so they can be initialized only when needed and disposed of when they're not. More on that here.

To use GetIt scopes using injectable you simply annotate the dependencies that are meant to be registered in a different scope with @Scope('scope-name') or pass in the scope name to Injectable or its subs like so @Injectable(scope: 'scope-name').

dependencies tagged with a scope name will be generated inside of a separate init method than the other main-scope dependencies.
e.g.

// @Scope('auth') this works too  
@Injectable(scope: 'auth')
class AuthController{}  

when you're ready to use the auth-scope, call the generated scope-init method or extension.

 // using extensions  
getIt.initAuthScope();
// using methods  
initAuthScope(getIt);

// scope-init method will return future if it has pre-resolved dependencies  
// so make sure you await it  
await getIt.initAuthScope();

Including microPackages and external modules

MicroPackages are sub packages that can be depended on and used by the root package, packages that's annotated as micro will generate a MicroPackageModule instead of an init-method and the initiation of those modules is done automatically by the root package's init-method.
so all you have to do is annotate the package as a microPackage by using the named constructor @InjectableInit.microPackage()

// @microPackageInit => short const  
@InjectableInit.microPackage()
initMicroPackage(){} // will not be called but needed for code generation  
Generated Code:
class AwesomePackageModule extends MicroPackageModule {
  @override
  FutureOr<void> init(_i1.GetItHelper gh) {
    gh.factory<Dep>(() => Dep());
    gh.factory<Calculator>(() => Calculator(gh<Dep>()));
  }}  

By default injectable will automatically include all MicroPackagesModules in the project directory unless the includeMicroPackages flag inside of @InjectableInit is set to false.

@InjectableInit(includeMicroPackages: false)

it's also possible to include micro local or external modules manually by passing them to the externalPackageModules property inside of @injectableInit so they're initialized with the rest of the local dependencies.
Note: Modules assigned to externalPackageModulesBefore will be initialized before the root dependencies; Modules assigned to externalPackageModulesAfter will be initialized after the root dependencies;

@InjectableInit(
  externalPackageModulesBefore: [
    ExternalModule(AwesomePackageModule),
    ExternalModule(ThirdPartyMicroModule),
  ],
  externalPackageModulesAfter: [
    ExternalModule(CoolPackageModule),
  ],)
void configureDependencies() {}
Initializing modules inside of scopes

External Modules can be initialized inside of specific scopes by simply assigning a scope to ExternalModule.

@InjectableInit(
  externalPackageModulesBefore: [
    ExternalModule(AwesomePackageModule, scope: 'awesome'),
  ], )
void configureDependencies() {}

then a scope initialization method/extension will be generated.

 await getIt.initAwesomeScope()

Problems with the generation?

Make sure you always Save your files before running the generator, if that does not work you can always try to clean and rebuild.

flutter packages pub run build_runner clean  

Support the Library

  • You can support the library by staring it on Github && liking it on pub or report any bugs you encounter.
  • also, if you have a suggestion or think something can be implemented in a better way, open an issue and let's talk about it.

카테고리

의존성

의존성 목록 2 개

소스 저장소

이 패키지를 사용하는 프로젝트

순위