customField<T> method
- String label, {
- required T initialValue,
- required InputParser<
T> parser, - required ValueFormatter<
T> formatter,
Creates a knob for a generic type T
controlled by a text field
in the UI.
You can use this to create custom knobs for editing values of type T
using a text field.
The label
specifies the text displayed in the UI for this knob.
It also uniquely identifies the knob, ensuring its state persists across
hot reloads.
The initialValue
defines the state of the knob when first created
and when the initial knob preset is selected.
The parser
function parses the user input String
and returns an InputParseResult.
If the input is valid, it should return an InputParseSuccess
with the parsed value of type T
.
If the input is invalid, it should return an InputParseError
with a short error message.
The parser
is allowed to accept multiple formats
that parse to the same value.
The formatter
function converts a value of type T
back into a String
representation.
Ideally parsing this formatted string yields an InputParseSuccess
with the original value.
See the example below for how to use this to create a BigInt knob:
extension BigIntKnobExtension on KnobsComposer {
WritableKnob<BigInt> bigInt(
String label, {
required BigInt initialValue,
}) {
return customField(
label,
initialValue: initialValue,
parser: _bigIntInputParser,
formatter: _bigIntInputFormatter,
);
}
}
extension NullableBigIntKnobExtension on NullableKnobsComposer {
WritableKnob<BigInt?> bigInt(
String label, {
required BigInt initialValue,
bool initiallyNull = false,
}) {
return customField(
label,
initialValue: initialValue,
parser: _bigIntInputParser,
formatter: _bigIntInputFormatter,
initiallyNull: initiallyNull,
);
}
}
InputParseResult<BigInt> _bigIntInputParser(String input) {
final trimmedInput = input.trim();
if (trimmedInput.isEmpty) {
return InputParseSuccess(BigInt.zero);
}
final parsedValue = BigInt.tryParse(trimmedInput);
return parsedValue != null
? InputParseSuccess(parsedValue)
: InputParseError('Invalid BigInt format');
}
String _bigIntInputFormatter(BigInt value) => value.toString();
Implementation
WritableKnob<T> customField<T>(
String label, {
required T initialValue,
required InputParser<T> parser,
required ValueFormatter<T> formatter,
}) {
return makeRegularKnob(
label,
initialValue: initialValue,
knobBuilder: (context, valueNotifier) => _CustomFieldKnob(
valueNotifier: valueNotifier,
parser: parser,
formatter: formatter,
isMultiLine: false,
enabled: true,
),
rebuildKnobBuilderOnChange: false,
);
}