setUserPropertyByPath method

Future<void> setUserPropertyByPath(
  1. String propertyPath,
  2. dynamic newValue
)

Sets a property value for the current user by a given path within their JSON data.

This method retrieves the current user's data and ensures it is in JSON format. It then navigates through the user's data based on the specified property path and sets the new value. If the path includes non-existing nested properties, it creates them along the way.

  • propertyPath: A dot-separated string indicating the path to the property to be set.
  • newValue: The new value to be assigned to the property at the specified path.

Example:

await setUserPropertyByPath('preferences.notifications.email', true);

Returns a Future that completes when the value has been set.

Implementation

Future<void> setUserPropertyByPath(String propertyPath, dynamic newValue) async {
  try {
    currentUser = null;

    // Retrieve the current user's data.
    final currentUserData = await getCurrentUser() as dynamic;

    // Check if the currentUserData is already a JSON string, if not, convert it.
    var userJson = currentUserData;
    if (currentUserData is! String) {
      userJson = json.encode(currentUserData);
    }

    // Parse the JSON string into a mutable map.
    final Map<String, dynamic> userMap = json.decode(userJson);

    // Split the property path and iterate through the path to get to the nested map.
    final List<String> pathParts = propertyPath.split('.');
    Map<String, dynamic> currentLevel = userMap;
    String lastKey = pathParts.removeLast();
    for (String part in pathParts) {
      if (currentLevel[part] is! Map) {
        currentLevel[part] = {}; // Create a new map if the nested property does not exist.
      }
      currentLevel = currentLevel[part];
    }

    // Set the new value at the specified path.
    currentLevel[lastKey] = newValue;

    await CoffeeStorage.setLoggedUser(fromJson(userMap));

    // Save the modified user data back to the storage.
    //await CoffeeStorage.setUserProperty(await getCurrentUser(), 'userData', json.encode(userMap));
    // ignore: empty_catches
  } catch (e) { }
}