toQueryParameters method

String toQueryParameters({
  1. SelectArrayFormat arrayFormat = SelectArrayFormat.repeat,
  2. String delimiter = ',',
  3. bool encode = true,
})

Converts this selection tree into a URL query string such as cate1=a&cate2=b, with the multi-value layout controlled by arrayFormat.

The key/value pairs are derived from toQueryMap; see there for how a selection tree maps to keys and values. Given {cate1: [l2-a, l2-b]}:

When encode is true (the default), keys and values are percent-encoded with Uri.encodeQueryComponent. Set it to false only when the caller handles encoding.

Returns an empty string when nothing is selected.

Implementation

String toQueryParameters({
  SelectArrayFormat arrayFormat = SelectArrayFormat.repeat,
  String delimiter = ',',
  bool encode = true,
}) {
  final map = toQueryMap();
  if (map.isEmpty) return '';

  String enc(String component) =>
      encode ? Uri.encodeQueryComponent(component) : component;
  String pair(String key, String value) => '${enc(key)}=${enc(value)}';

  final pairs = <String>[];
  for (final mapEntry in map.entries) {
    final key = mapEntry.key;
    final values = mapEntry.value;
    switch (arrayFormat) {
      case SelectArrayFormat.repeat:
        pairs.addAll(values.map((value) => pair(key, value)));
      case SelectArrayFormat.brackets:
        pairs.addAll(values.map((value) => pair('$key[]', value)));
      case SelectArrayFormat.indices:
        for (var i = 0; i < values.length; i++) {
          pairs.add(pair('$key[$i]', values[i]));
        }
      case SelectArrayFormat.comma:
        pairs.add('${enc(key)}=${values.map(enc).join(',')}');
      case SelectArrayFormat.delimited:
        pairs.add('${enc(key)}=${values.map(enc).join(delimiter)}');
    }
  }
  return pairs.join('&');
}