getRequiredProp<V> method
V
getRequiredProp<V>(
- V accessProp(
- T spiedView
- required V orElse(),
Returns the value of the prop read within accessProp
if it's specified,
or the result of orElse
otherwise.
Useful for safely accessing required props in a "partial" props map that may not contain them.
See also: getRequiredPropOrNull.
For example:
class FooProps on UiProps {
late String requiredProp;
}
void example(FooProps props) {
// Unsafe: this will throw if requiredProp is not specified
final requiredProp = props.requiredProp;
final requiredPropOrDefault =
props.getRequiredProp((p) => p.requiredProp, () => 'default value');
}
Implementation
V getRequiredProp<V>(V Function(T spiedView) accessProp, {required V Function() orElse}) {
if (!containsProp(accessProp)) return orElse();
// Provide a more helpful error when a non-nullable prop is specified with `null` somehow.
assert(() {
try {
accessProp(this);
} on TypeError catch (e, st) {
final key = getPropKey(accessProp);
final value = this[key];
if (value == null) {
throw AssertionError('Error reading typed prop, likely due to props map containing explicit `null` value:'
' `"$key": null`.\nOriginal error: $e\n$st');
}
rethrow;
}
return true;
}());
return accessProp(this);
}