requireString function

String requireString(
  1. CrossmintJsonMap map,
  2. String key, {
  3. required String entity,
})

Returns the non-empty string at key in map, or throws a typed CrossmintDeserializationException naming entity and key.

Use this in fromJson constructors instead of bare as String casts so missing or malformed fields surface as a typed exception with usable context, rather than an opaque TypeError from a failed cast.

Implementation

String requireString(
  CrossmintJsonMap map,
  String key, {
  required String entity,
}) {
  final Object? value = map[key];
  if (value is String && value.isNotEmpty) {
    return value;
  }
  throw CrossmintDeserializationException(
    'Expected non-empty string for "$key" while parsing $entity.',
    entity: entity,
    field: key,
    cause: map,
  );
}