Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Singleton vs Singleton in Dart

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?

like image 596
Benjamin Avatar asked Dec 17 '22 14:12

Benjamin


2 Answers

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.

like image 76
Guru Prasad mohapatra Avatar answered Dec 20 '22 03:12

Guru Prasad mohapatra


"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

like image 29
Denis G Avatar answered Dec 20 '22 03:12

Denis G