optionalString function
The string at key when there is one, null when the field is absent or null,
and a FormatException when it is present as something other than a string.
The distinction matters: a field the API legitimately omits is not the same as a field it sent as a number, and only the second is a fault worth reporting.
Implementation
String? optionalString(Map<String, dynamic> json, String key, String what) {
final value = json[key];
if (value == null) return null;
if (value is String) return value;
throw FormatException(
'$what expected "$key" to be a string, got ${_describe(value)}',
);
}