requireString function

String requireString(
  1. Map<String, dynamic> json,
  2. String key,
  3. String what, {
  4. bool allowEmpty = false,
})

The string at key, or a FormatException naming the field that was wrong.

asJsonObject gets a body as far as "this is an object", and every parser then reached into it with json['token'] as String. On a response that was not the promised shape - an API version skew, a partial write, a proxy rewriting the body - that raises type 'Null' is not a subtype of type 'String' in type cast from inside the SDK, naming neither the field nor the endpoint. Note that strict-casts cannot catch those: it forbids implicit casts, and every one of them was explicit.

An empty string counts as absent unless allowEmpty is set. Every field this guards is a token, an identifier or a URL, and none of those mean anything empty - a {"token": ""} response would otherwise be stored and then fail on the request it was stored for.

Implementation

String requireString(
  Map<String, dynamic> json,
  String key,
  String what, {
  bool allowEmpty = false,
}) {
  final value = json[key];

  if (value is String && (allowEmpty || value.isNotEmpty)) return value;

  throw FormatException(
    '$what expected a "$key" string, got ${_describe(value)}',
  );
}