encodePath function

String encodePath(
  1. String template, {
  2. Map<String, String>? pathMap,
  3. Map<String, String>? params,
})

Create a path string from the provided template, path mappings, and parameters.

Denoted segments in the template will be replaced with the given path mappings. For example, with the given template /devices/:deviceId/equipment/:equipId and the given pathMap, { deviceId: DEVICE123, equipId: EQUIP123}, the resulting path /devices/DEVICE123/equipment/EQUIP123 will be created.

The query string will then be appended based on the given parameters map.

Implementation

String encodePath(
  String template, {
  Map<String, String>? pathMap,
  Map<String, String>? params,
}) {
  String onMatch(Match match) {
    final result = match.group(0)!; // should always have a match
    final key = result.substring(1);

    if (pathMap == null) {
      throw ArgumentError(
        'The given pathMap, \'$pathMap\', must not be '
        'null for this template: \'$template\'',
      );
    }

    final value = pathMap[key];

    if (value == null) {
      throw ArgumentError(
        'The given pathMap, \'$pathMap\', does not '
        'match this template: \'$template\'',
      );
    }

    return Uri.encodeComponent(value);
  }

  var path = template.splitMapJoin(
    _kReplacePattern,
    onMatch: onMatch,
  );

  if (params != null && params.isNotEmpty) {
    bool isNotEmpty(MapEntry<String, String> param) {
      return param.key.isNotEmpty && param.value.isNotEmpty;
    }

    String toQuery(MapEntry<String, String> param) {
      final key = Uri.encodeQueryComponent(param.key);
      final value = Uri.encodeQueryComponent(param.value);
      return '$key=$value';
    }

    // ignore: prefer_interpolation_to_compose_strings
    path += '?' +
        params.entries
            .where(isNotEmpty)
            .map(toQuery)
            .toList()
            .sorted()
            .join('&');
  }

  return path;
}