toggleNullification method

  1. @protected
void toggleNullification(
  1. BuildContext context, {
  2. required bool nullify,
})
inherited

Adds/removes Field.nullabilitySymbol to/from all fields depending on the nullify state. If nullify is true, the Field.nullabilitySymbol is added. If nullify is false, the Field.nullabilitySymbol is removed.

Implementation

@protected
void toggleNullification(
  BuildContext context, {
  required bool nullify,
}) {
  assert(
    isNullable,
    'toggleNullification is only available for nullable composables',
  );

  // NOTE:
  // Currently, we are nullifying the [FieldsComposable] by nullifying all
  // the fields in the group. A better approach would be by nullifying the
  // group itself only (for example: `group={...}` > `group=?{...}).
  // This approach is not currently feasible as all knobs are located under
  // the same group. This is a limitation of the current implementation.
  // We can revisit in future major releases.

  final state = WidgetbookState.of(context);
  final groupMap = FieldCodec.decodeQueryGroup(
    state.queryParams[groupName],
  );

  fields.forEach((field) {
    // If the field is not present in the `groupMap`, we set it to its
    // initial value or default value.
    //
    // This is used when user first interacts with a nullable field.
    if (!groupMap.containsKey(field.name)) {
      final value =
          field.initialValueStringified ?? field.defaultValueStringified;
      state.updateQueryField(
        group: groupName,
        field: field.name,
        value: nullify ? '${Field.nullabilitySymbol}${value}' : value,
      );
      return;
    }

    final value = groupMap[field.name];
    if (value == null) return;

    final rawValue = value.replaceFirst(Field.nullabilitySymbol, '');
    final nullishValue = '${Field.nullabilitySymbol}$rawValue';

    state.updateQueryField(
      group: groupName,
      field: field.name,
      value: nullify ? nullishValue : rawValue,
    );
  });
}