简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM