String Knob

The String knob renders a text field in the Widgetbook UI where you can dynamically enter a string value for a widget property. This is particularly useful for properties that require a string input, such as a name or description.

Varients

The String knob has two variants:

  • context.knobs.string(): This variant allows you to enter a string value. It does not accept null values.
  • context.knobs.stringOrNull(): This variant allows you to enter a string value or null. It is useful when the property can be optional.

Properties

In addition to the knob's base properties, the String knob includes the following:

maxLinesintoptional

The number of lines the text field can display. Defaults to 1.

context.knobs.string()

Example

Usage

To use a String knob, call the context.knobs.string() method.

Example: String Knob
@UseCase(type: MyWidget, name: 'Default')
Widget buildUseCase(BuildContext context) {
  return MyWidget(
    name: context.knobs.string(label: 'Name', initialValue: 'John Doe'), 
  );
}

context.knobs.stringOrNull()

Example

Usage

To use the nullable String knob, call the context.knobs.stringOrNull() method.

Example: Nullable String Knob
@UseCase(type: MyWidget, name: 'Default')
Widget buildUseCase(BuildContext context) {
  return MyWidget(
    name: context.knobs.stringOrNull(label: 'name', initialValue: 'John Doe'), 
  );
}

Multi-snapshot Support

Multi-snapshot support allows you to generate multiple screenshots of a single use case with varying values using KnobsConfigs and AddonsConfigs.

Regular String Knob

Example: StringKnobConfig
import 'package:widgetbook/widgetbook.dart';

@UseCase(
  type: MyWidget,
  name: 'Default',
  cloudKnobsConfigs: { /
    'short name': [StringKnobConfig('name', 'John Doe')], 
    'long name': [StringKnobConfig('name', 'Maximilian Mustermann')], 
  }, 
)
Widget buildUseCase(BuildContext context) {
  return MyWidget(
    name: context.knobs.string(label: 'name', initialValue: 'John Doe'),
  );
}

Nullable String Knob

Example: NullKnobConfig
import 'package:widgetbook/widgetbook.dart';

@UseCase(
  type: MyWidget,
  name: 'Default',
  cloudKnobsConfigs: { /
    'no name': [NullKnobConfig('name')], 
    'with name': [StringKnobConfig('name', 'John Doe')], 
  }, 
)
Widget buildUseCase(BuildContext context) {
  return MyWidget(
    name: context.knobs.stringOrNull(label: 'name'),
  );
}