optionalStringList function
The strings at key when there are any, null when the field is absent, and a
FormatException when it is present as something other than a list of
strings.
The element cast is the point: (json['roles'] as List?)?.map((e) => e as String) fails on the element, so a single non-string in the list produced a
type error naming neither the field nor the value.
Implementation
List<String>? optionalStringList(
Map<String, dynamic> json,
String key,
String what,
) {
final value = json[key];
if (value == null) return null;
if (value is List) {
final strings = <String>[];
for (final element in value) {
if (element is! String) {
throw FormatException(
'$what expected "$key" to hold strings, found ${_describe(element)}',
);
}
strings.add(element);
}
return strings;
}
throw FormatException(
'$what expected "$key" to be a list, got ${_describe(value)}',
);
}