buildQueryString function

String buildQueryString(
  1. Map<String, dynamic> query
)

Serializes a map of query parameters into a URL query string prefixed with ?.

Handles percent-encoding of keys and values, unrolls Iterable values into repeated keys, and ignores entries with null values. Returns an empty string if query is empty or contains only null values.

Safe for both server-side rendering (SSR) and browser environments.

final qs = buildQueryString({
  'q': 'shoes',
  'page': 2,
  'tag': ['sale', 'men'],
  'empty': null,
});
print(qs); // '?q=shoes&page=2&tag=sale&tag=men'

Implementation

String buildQueryString(Map<String, dynamic> query) {
  if (query.isEmpty) return '';
  final pairs = <String>[];
  query.forEach((key, value) {
    if (value == null) return;
    final encodedKey = Uri.encodeQueryComponent(key);
    if (value is Iterable) {
      for (final item in value) {
        if (item == null) continue;
        pairs.add('$encodedKey=${Uri.encodeQueryComponent(item.toString())}');
      }
    } else {
      pairs.add('$encodedKey=${Uri.encodeQueryComponent(value.toString())}');
    }
  });
  return pairs.isEmpty ? '' : '?${pairs.join('&')}';
}