Lazy Singleton vs Singleton in Dart
Solution 1
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.
Solution 2
"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
Benjamin
Hi! I'm a sophomore in High School and I love computers & programming. I'm familiar with Flutter & Dart. I also do web development and am pretty good at HTML, CSS, and JS. I typically use the Angular framework with TypeScript. TL;DR Languages I know: HTML, CSS, JS Dart Lua TypeScript (if you count that as a language) Frameworks I know: Angular Flutter Svelte
Updated on December 16, 2022Comments
-
Benjamin over 1 year
I'm using the get_it package and you get two options for registering Singletons, lazy and I guess "regular" (
GetIt.instance.registerLazySingleton
andGetIt.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?