joinPath function

String joinPath(
  1. String base,
  2. List<String> segments
)

Appends segments to base, encoding each one and collapsing the separators so a trailing slash on base cannot produce an empty path segment.

Empty segments are skipped rather than encoded, since they would otherwise produce the doubled separator this exists to prevent.

Implementation

String joinPath(String base, List<String> segments) {
  final trimmed = base.endsWith('/')
      ? base.substring(0, base.length - 1)
      : base;

  final encoded = segments
      .where((segment) => segment.isNotEmpty)
      .map(Uri.encodeComponent);

  if (encoded.isEmpty) return trimmed;

  return '$trimmed/${encoded.join('/')}';
}