I am working with singleton pattern, and I have managed the dependency and parameter injections like this:
LocalizationClientComponent._();
/// Singleton instance of the [LocalizationClientComponent] class.
static final instance = LocalizationClientComponent._();
static bool _injectedDependencies = false;
static bool _injectedParams = false;
late final DeviceInfoRepository _deviceInfoRepository;
late final MapapiRepository _mapapiRepository;
late final SensorsRepository _sensorsRepository;
late final LocationRepository _locationRepository;
late final BluetoothRepository _bluetoothRepository;
late final WifiRepository _wifiRepository;
void injectDependencies({
required DeviceInfoRepository deviceInfoRepository,
required MapapiRepository mapapiRepository,
required SensorsRepository sensorsRepository,
required LocationRepository locationRepository,
required BluetoothRepository bluetoothRepository,
required WifiRepository wifiRepository,
}) {
if (_injectedDependencies) return;
_deviceInfoRepository = deviceInfoRepository;
_mapapiRepository = mapapiRepository;
_sensorsRepository = sensorsRepository;
_locationRepository = locationRepository;
_bluetoothRepository = bluetoothRepository;
_wifiRepository = wifiRepository;
_injectedDependencies = true;
}
Then the same thing for parameters:
void injectParams({
required String email,
required String password,
required Duration postFrequency,
required int sensorListLength,
}) {
if (_injectedParams) return;
_postFrequency = postFrequency;
_sensorListLength = sensorListLength;
_telemetryEvent = TelemetryEvent(_sensorListLength);
_injectedParams = true;
}
After that, I made this method to control whether params and dependencies are injected:
void _handleInitError() {
final StringBuffer errorMessage = StringBuffer();
if (!_injectedDependencies) {
errorMessage
..write(
'Dependencies are not injected. Use injectDependencies() before using any other methods.',
)
..write('\n');
}
if (!_injectedParams) {
errorMessage.write(
'Parameters are not injected. Use injectParams() before using any other methods.',
);
}
if (errorMessage.isNotEmpty) {
throw Exception(errorMessage.toString());
}
}
Now, I am adding _handleInitError()
to all other methods like this:
Future<bool> openAppSettings() async {
_handleInitError();
return _locationRepository.openAppSettings();
}
Future<bool> openLocationSettings() async {
_handleInitError();
return _locationRepository.openLocationSettings();
}
Future<bool> requestLocationPermission() {
_handleInitError();
return _locationRepository.requestLocationPermission();
}
Future<bool> activateLocationService() async {
_handleInitError();
return _locationRepository.activateLocationService();
}
Future<bool> turnOnWifi() async {
_handleInitError();
return _wifiRepository.turnOnWifi();
}
Is there a better way than adding all methods to _handleInitError()
?
Is there a way to automatically execute this method before any method?
Aucun commentaire:
Enregistrer un commentaire