EzConfig constructor

EzConfig({
  1. required List<String> assetPaths,
  2. required SharedPreferences preferences,
  3. Map<String, dynamic>? customDefaults,
})

Factory/external/initialization constructor

Implementation

factory EzConfig({
  required List<String> assetPaths,
  required SharedPreferences preferences,
  Map<String, dynamic>? customDefaults,
}) {
  if (_instance == null) {
    // Load any custom defaults
    Map<String, dynamic> mergedDefaults = new Map.from(defaultConfig);
    if (customDefaults != null) mergedDefaults.addAll(customDefaults);

    Map<String, dynamic> prefs = new Map.from(mergedDefaults);

    // Load the keys that have been overwritten
    List<String> overwritten =
        prefs.keys.toSet().intersection(preferences.getKeys()).toList();

    overwritten.forEach((key) {
      dynamic value = prefs[key];
      dynamic userPref;

      switch (value.runtimeType) {
        case int:
          userPref = preferences.getInt(key);
          break;
        case bool:
          userPref = preferences.getBool(key);
          break;
        case double:
          userPref = preferences.getDouble(key);
          break;
        case String:
          userPref = preferences.getString(key);
          break;
        case List<String>:
          userPref = preferences.getStringList(key);
          break;
        default:
          break;
      }

      if (userPref != null) prefs[key] = userPref;
    });

    // Load hand setting
    bool? isRight = preferences.getBool(isRightKey);
    final Hand dominantSide =
        (isRight == null || isRight == true) ? Hand.right : Hand.left;

    _instance = EzConfig._(
      assets: assetPaths,
      preferences: preferences,
      defaults: mergedDefaults,
      prefs: prefs,
      fontFamily: googleStyles[(prefs[fontFamilyKey])]?.fontFamily,
      dominantSide: dominantSide,
    );
  }

  return _instance!;
}