getStorageItem function

Future getStorageItem({
  1. required String key,
})

Retrieves the value associated with the given key from the storage. If the value is null, returns null. If the value is a JSON string, decodes it and returns the value of the key. If the value is not a JSON string, returns the value as is. Throws an exception if there is an error while retrieving the item.

Example usage:

final storageUser = await getStorageItem(key: 'sgm_user');

Implementation

Future<dynamic> getStorageItem({required String key}) async {
  try {
    final prefs = await SharedPreferences.getInstance();
    final value = prefs.getString(key);

    if (value == null) {
      // If the value is null, return null
      return null;
    }

    try {
      // If the value is a json string, decode it and return the value of the key
      return json.decode(value);
    } catch (e) {
      // If the value is not a json string, return the value
      return value;
    }
  } catch (e) {
    throw Exception('getItem error: $e');
  }
}