set method

Future<bool> set(
  1. String key,
  2. dynamic value
)

Item setter

@param key String @param value any @returns Future

Implementation

Future<bool> set(String key, value) async {
  SharedPreferences prefs = await _prefs;

  Map<TypeCheck, Future<bool> Function(String key, dynamic value)> typeMap =
      <TypeCheck, Future<bool> Function(String key, dynamic value)>{
    const TypeCheck<String>(): (key, value) async =>
        await prefs.setString(key, value),
    const TypeCheck<int>(): (key, value) async =>
        await prefs.setInt(key, value),
    const TypeCheck<bool>(): (key, value) async =>
        await prefs.setBool(key, value),
    const TypeCheck<double>(): (key, value) async =>
        await prefs.setDouble(key, value),
    const TypeCheck<List>(): (key, value) async =>
        await prefs.setStringList(key, value),
    const TypeCheck<DateTime>(): (key, value) async => await prefs.setString(
        key, jsonEncode((value as DateTime?)?.toIso8601String())),
    const TypeCheck<Map>(): (key, value) async => await prefs.setString(
        key, jsonEncode(MapSerializer.mapToJsonMap(value))),
  };

  // Detect function based on item type
  try {
    var function = typeMap.entries
        .firstWhereOrNull((type) => type.key.matches(value))
        ?.value;
    if (function == null) {
      return await prefs.setString(key, jsonEncode(value));
    }
    return function(key, value);
  } catch (e) {
    throw Exception(
        "Key or value are not the correct type. type:${value.runtimeType}");
  }
}