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.

Implementation

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

    if (on != _originalOn) {
      toReturn[ApiFields.isOn] = on.toJson(optimizeFor: OptimizeFor.putFull);
    }

    if (dimming != _originalDimming) {
      toReturn[ApiFields.dimming] =
          dimming.toJson(optimizeFor: OptimizeFor.putFull);
    }

    if (xy != _originalXy) {
      toReturn[ApiFields.color] = {
        ApiFields.xy: xy.toJson(optimizeFor: OptimizeFor.putFull)
      };
    }

    if (colorTemperature != _originalColorTemperature) {
      toReturn[ApiFields.colorTemperature] =
          colorTemperature.toJson(optimizeFor: OptimizeFor.putFull);
    }

    if (gradient != _originalGradient) {
      toReturn[ApiFields.gradient] =
          gradient.toJson(optimizeFor: OptimizeFor.putFull);
    }

    if (effect != _originalEffect) {
      toReturn[ApiFields.effects] = {ApiFields.effect: effect};
    }

    if (durationMilliseconds != _originalDurationMilliseconds) {
      toReturn[ApiFields.dynamics] = {
        ApiFields.duration: durationMilliseconds
      };
    }

    return toReturn;
  }

  // DEFAULT
  return {
    ApiFields.isOn: on.toJson(optimizeFor: optimizeFor),
    ApiFields.dimming: dimming.toJson(optimizeFor: optimizeFor),
    ApiFields.color: {ApiFields.xy: xy.toJson(optimizeFor: optimizeFor)},
    ApiFields.colorTemperature:
        colorTemperature.toJson(optimizeFor: optimizeFor),
    ApiFields.gradient: gradient.toJson(optimizeFor: optimizeFor),
    ApiFields.effects: {ApiFields.effect: effect},
    ApiFields.dynamics: {ApiFields.duration: durationMilliseconds},
  };
}