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.
The String knob has two variants:
context.knobs.string(): This variant allows you to enter a string value. It does not acceptnullvalues.context.knobs.stringOrNull(): This variant allows you to enter a string value ornull. It is useful when the property can be optional.
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.
To use a String knob, call the context.knobs.string() method.
dartExample: String Knob
@UseCase(type: MyWidget, name: 'Default')
Widget buildUseCase(BuildContext context) {
return MyWidget(
name: context.knobs.string(label: 'Name', initialValue: 'John Doe'),
);
}To use the nullable String knob, call the context.knobs.stringOrNull() method.
dartExample: 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 allows you to generate multiple screenshots of a single use case with varying values using KnobsConfigs and AddonsConfigs.
dartExample: 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'),
);
}dartExample: 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'),
);
}
