toJson method

Map<String, dynamic> toJson({
  1. OptimizeFor optimizeFor = OptimizeFor.put,
})

Converts this object into JSON format.

optimizeFor lets the program know what information to include in the JSON data map.

  • OptimizeFor.put (the default value) is used when making a data map that is being placed in a PUT request. This only includes data that has changed.
  • OptimizeFor.putFull is used when a parent object updates; so, all of the children are required to be present for the PUT request.
  • OptimizeFor.post is used when making a data map for a POST request.
  • OptimizeFor.dontOptimize is used to get all of the data contained in this object.

Throws GradientException if points has is not in the proper range. It must either have 0 elements or between 2 and 5 (inclusive), and optimizeFor is not set to OptimizeFor.dontOptimize.

Throws InvalidValueException if mode is empty and optimizeFor is not set to OptimizeFor.dontOptimize.

Implementation

Map<String, dynamic> toJson({OptimizeFor optimizeFor = OptimizeFor.put}) {
  // Make sure data is valid.
  if (!identical(optimizeFor, OptimizeFor.dontOptimize)) {
    // Validate [points].
    if (!Validators.isValidGradient(points)) {
      throw GradientException.withValue(points.length);
    }

    // Validate [mode].
    if (!Validators.isValidValue(mode, modeValues)) {
      if (!identical(optimizeFor, OptimizeFor.put) || mode != originalMode) {
        throw InvalidValueException.withValue(mode, modeValues);
      }
    }
  }

  // PUT
  if (identical(optimizeFor, OptimizeFor.put)) {
    Map<String, dynamic> toReturn = {};

    if (!const DeepCollectionEquality.unordered()
        .equals(points, originalPoints)) {
      toReturn[ApiFields.points] = points
          .map((point) => {
                ApiFields.color: {
                  ApiFields.xy: point.toJson(optimizeFor: OptimizeFor.putFull)
                }
              })
          .toList();
    }

    if (mode != originalMode) {
      toReturn[ApiFields.mode] = mode;
    }

    return toReturn;
  }

  // PUT FULL
  if (identical(optimizeFor, OptimizeFor.putFull)) {
    return {
      ApiFields.points: points
          .map((point) => {
                ApiFields.color: {
                  ApiFields.xy: point.toJson(optimizeFor: OptimizeFor.putFull)
                }
              })
          .toList(),
      ApiFields.mode: mode,
    };
  }

  // DEFAULT
  return {
    ApiFields.points: points
        .map(
          (point) => {
            ApiFields.color: {
              ApiFields.xy: point.toJson(
                optimizeFor: identical(optimizeFor, OptimizeFor.dontOptimize)
                    ? optimizeFor
                    : OptimizeFor.putFull,
              )
            }
          },
        )
        .toList(),
    ApiFields.mode: mode,
    ApiFields.modeValues: modeValues,
  };
}