Line data Source code
1 : /// Abstract class to help dependency injection. 2 : abstract class Injection { 3 6 : static final Injection _instance = _DiImpletation(); 4 : 5 6 : static final Injection I = _instance; 6 : 7 : void factory<T extends Object>(FactoryFunc<T> factoryFunc); 8 : 9 : T get<T extends Object>(); 10 : 11 : void clearFactories(); 12 : } 13 : 14 : typedef FactoryFunc<T> = T Function(); 15 : 16 : class _DiImpletation<T> implements Injection { 17 : final _factories = <Type, Object>{}; 18 : 19 2 : @override 20 : // ignore: avoid_shadowing_type_parameters 21 : void factory<T extends Object>(FactoryFunc<T> factoryFunc) { 22 : final key = T; 23 : 24 4 : if (!_factories.containsKey(key)) { 25 6 : _factories[key] = factoryFunc(); 26 : } 27 : } 28 : 29 2 : @override 30 : // ignore: avoid_shadowing_type_parameters 31 : T get<T extends Object>() { 32 4 : final result = _factories[T]; 33 : 34 : if (result == null) { 35 0 : throw Exception('Factory is not registered for $T'); 36 : } 37 : 38 : return result as T; 39 : } 40 : 41 2 : @override 42 : void clearFactories() { 43 4 : _factories.clear(); 44 : } 45 : }