coerce function

dynamic coerce(
  1. String value
)

Implementation

dynamic coerce(String value) {
  final attempts = [
    () {
      // Keep leading-zero forms as strings (`007`, `05`, `-01`). Numeric
      // parse would drop the zeros, and String query/header bindings that
      // stringify coerced values would then return the wrong wire form.
      if (_hasLeadingZero(value)) {
        throw const FormatException();
      }
      return int.parse(value);
    },
    () {
      if (_hasLeadingZero(value)) {
        throw const FormatException();
      }
      return double.parse(value);
    },
    () {
      final decoded = jsonDecode(value);
      return decoded is Map || decoded is List
          ? coerceDynamic(decoded)
          : decoded;
    },
    () => switch (value) {
          'true' => true,
          'false' => false,
          _ => throw const FormatException(),
        },
  ];

  for (final attempt in attempts) {
    try {
      final result = attempt();

      return result;
    } catch (_) {}
  }

  return value;
}