Lazy Singleton vs Singleton in Dart
Asked Answered
U

3

19

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?

Uniat answered 23/12, 2019 at 18:47 Comment(0)
V
34

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.

Vanpelt answered 24/12, 2019 at 8:17 Comment(0)
Z
6

"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

Zipangu answered 23/12, 2019 at 22:44 Comment(0)
S
0

Singletons and LazySingleton both refer to a class that is first initialised before using it for the first time. And after that, it can be used globally to access it. It's mostly used to save memory and resources in the project.

Shrum answered 12/7, 2023 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.