I'm using the get_it package and you get two options for registering Singletons, lazy and I guess "regular" (GetIt.instance.registerLazySingleton
and GetIt.instance.registerSingleton
respectively) Here's one of the classes that's registered as a plain Singleton:
class AndroidDetails {
static final DeviceInfoPlugin _deviceInfoPlugin = DeviceInfoPlugin();
Map<String, dynamic> _deviceData = {};
AndroidDetails() {
_init().then((_) => getIt.signalReady(this));
}
Future<void> _init() async {
try {
AndroidDeviceInfo _deviceInfo = await deviceInfoPlugin.androidInfo;
_deviceData = _getDeviceData(_deviceInfo);
} on PlatformException {
_deviceData = <String, dynamic>{
'Error:': 'Failed to get platform version.',
};
}
}
Map<String, dynamic> _getDeviceData(AndroidDeviceInfo build) {
return <String, dynamic>{
'version.sdkInt': build.version.sdkInt,
};
}
bool canChangeStatusBarColor() {
if (_deviceData.isNotEmpty) {
return _deviceData['version.sdkInt'] >= 21;
}
return null;
}
bool canChangeNavbarIconColor() {
if (_deviceData.isNotEmpty) {
return _deviceData['version.sdkInt'] >= 27;
}
return null;
}
}
How it's registered:
// main.dart
getIt.registerSingleton<AndroidDetails>(AndroidDetails(), signalsReady: true);
My question is, what's the difference between a "normal" Singleton and a Lazy Singleton in Dart & the get_it package?
Both are Singletons
. But LazySingleton
refers to a class whose resource will not be initialised until its used for the 1st time. It's generally used to save resources and memory.
"Lazy" refers to initiating resources at the time of the first request instead at the time of declaration. More reading on the concept is here: https://en.wikipedia.org/wiki/Lazy_initialization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With