buildSwitch method

  1. @protected
Widget buildSwitch(
  1. BuildParameters params
)

Implementation

@protected
Widget buildSwitch(BuildParameters params) {
  var alias = params.props["alias"] ?? params.id;
  var enabled = parseBool(params.props["enabled"], defaultValue: true);
  var controlAffinity = params.props["direction"] == "leading"
      ? ListTileControlAffinity.leading
      : params.props["direction"] == "trailing"
          ? ListTileControlAffinity.trailing
          : ListTileControlAffinity.platform;

  Widget? title = builder.tryBuildWidget(params.context,
      params.widgets["titleWidget"], params.state, params.parentContext);
  title ??= params.props["title"] != null
      ? Text(properties.getText(params.props["title"], "titleMessage"))
      : null;
  Widget? subtitle = builder.tryBuildWidget(params.context,
      params.widgets["subtitleWidget"], params.state, params.parentContext);
  subtitle ??= params.props["subtitle"] != null
      ? Text(properties.getText(params.props["subtitle"], "titleMessage"))
      : null;

  var onChanged = events.getValueFunction<bool?>(params.context,
      params.actions["onChanged"], params.state, params.parentContext);
  var onSaved = params.props["onSaved"] ??
      (v) {
        if (alias != null) {
          params.state[alias] = v;
        }
      };

  return FormField<bool>(
    key:
        UniqueKey(), // otherwise on a ListView, FormField's state would override the real value when reusing widgets
    initialValue: parseBool(params.props["value"]),
    enabled: enabled,
    autovalidateMode: AutovalidateMode.disabled,
    validator: builder.getCheckboxValidator(params.props),
    onSaved: onSaved,
    builder: (state) {
      return SwitchListTile(
        key: properties.getKey(params.id),
        value: state.value ?? false,
        controlAffinity: controlAffinity,
        activeColor: tryParseColor(params.props["activeColor"]),
        hoverColor: tryParseColor(params.props["hoverColor"]),
        activeTrackColor: tryParseColor(params.props["activeTrackColor"]),
        inactiveThumbColor: tryParseColor(params.props["inactiveThumbColor"]),
        inactiveTrackColor: tryParseColor(params.props["inactiveTrackColor"]),
        shape: params.buildProp("shape"),
        title: title,
        subtitle: state.hasError
            ? Text(properties.getText(state.errorText!, "errorMessage"),
                style: TextStyle(
                    color: Theme.of(params.context).colorScheme.error))
            : subtitle,
        secondary: builder.tryBuildWidget(params.context,
            params.widgets["secondary"], params.state, params.parentContext),
        contentPadding: params.buildProp("contentPadding"),
        onChanged: enabled
            ? (val) {
                state.didChange(val);
                if (onChanged != null) {
                  onChanged(val);
                }
              }
            : null,
      );
    },
  );
}