import 'dart:async'; import 'package:get_it/get_it.dart'; import 'package:lszlgl/main.dart'; /// 依赖注入管理 /// /// ``` /// 简单使用 /// 添加注入: /// var user = Inject.put(UserBean(), dispose: (v) => v.dispose()); /// 添加注入(懒加载): /// Inject.putLazy(UserBean(), dispose: (v) => v.dispose()); /// /// 获取实例: /// var user = Inject.get(); /// /// 移除注入: /// Inject.remove(); /// ``` class Inject { Inject._(); /// 添加依赖注入 /// 注入后得到实例化对象, 也可以通过[get]方法得到对象. /// * [instance] 实例化对象 /// * [name] 注入多个同类型对象时,可以使用name来区分 /// * [dispose] 移除时回调方法 /// * [allowReassignment] 是否可以重复注册, 默认不可重复注册, 返回之前已有实例 /// static T put( T instance, { String? name, FutureOr Function(T)? dispose, bool allowReassignment = false, }) { GetIt.I.allowReassignment = true; // 不可重复注册, 已注册,则返回之前实例 if (!allowReassignment && GetIt.I.isRegistered(instanceName: name)) { logger.d('Inject put:$T 已被注册'); return get()!; } logger.d('Inject put:$T'); GetIt.I.registerSingleton( instance, instanceName: name, dispose: dispose, ); return instance; } /// 添加依赖注入 懒加载 /// 注入后不会立即实例化对象, 当调用[get]时才会实例化. /// * [factoryFunc] 实例化对象回调方法 /// * [name] 注入多个同类型对象时,可以使用name来区分 /// * [dispose] 移除时回调方法 static void putLazy( T Function() factoryFunc, { String? name, FutureOr Function(T)? dispose, bool allowReassignment = false, }) { GetIt.I.allowReassignment = true; if (!allowReassignment && GetIt.I.isRegistered(instanceName: name)) { logger.d('Inject putLazy:$T 已被注册'); return; } logger.d('Inject putLazy:$T'); GetIt.I.registerLazySingleton( factoryFunc, instanceName: name, dispose: dispose, ); } /// 移除依赖注入 /// * [instance] 通过实例移除 /// * [name] 通过名称移除 /// * [dispose] 移除时回调方法 static FutureOr remove({ Object? instance, String? name, FutureOr Function(T)? dispose, }) { logger.d('Inject remove:$T'); return GetIt.I.unregister( instance: instance, instanceName: name, disposingFunction: dispose, ); } /// 获取唯一实例 /// Model model = GdInject.get(); static T? get({String? name}) { logger.d('Inject get:$T'); return GetIt.I.get(instanceName: name); } /// 获取唯一实例,如果未注入依赖,将自动注入依赖 static T getAndPut( T instance, { String? name, FutureOr Function(T)? dispose, }) { // 已注册 if (GetIt.I.isRegistered(instanceName: name)) { return get(name: name)!; } return put(instance, name: name, dispose: dispose); } }