Map<String, String> parseQueryString(String query)

Source

Map<String, String> parseQueryString(String query) {
  _verifyQueryString(query);

  final parts = query.split('&');
  final Iterable<String> rawKeys = parts.map((s) => s.split('=').first);
  final List<String> values = parts.map((s) => s.split('=').last).toList();
  final map = {};
  final rootNamePattern = new RegExp(r'^([^\[]+)(.*)$');
  final contPattern = new RegExp(r'^\[(.*?)\](.*)$');
  dynamic nextValue() {
    return _raw.parseString(Uri.decodeQueryComponent(values.removeAt(0)));
  }
  for (var restOfKey in rawKeys) {
    final rootMatch = rootNamePattern.firstMatch(restOfKey);
    final rootKey = Uri.decodeQueryComponent(rootMatch[1]);
    final rootCont = rootMatch[2];
    if (rootCont == '') {
      map[rootKey] = nextValue();
      continue;
    }
    dynamic target = map;
    dynamic targetKey = rootKey;

    restOfKey = rootCont;

    while (contPattern.hasMatch(restOfKey)) {
      final contMatch = contPattern.firstMatch(restOfKey);
      final keyName = Uri.decodeQueryComponent(contMatch[1]);
      if (keyName == '') {
        target[targetKey] ??= [];
        (target[targetKey] as List).add(null);
        target = target[targetKey];
        targetKey = target.length - 1;
      } else if (new RegExp(r'^\d+$').hasMatch(keyName)) {
        final List targetList = target[targetKey] ??= [];
        final index = int.parse(keyName);
        if (targetList.length == index) {
          targetList.add(null);
        } else {
          targetList[index] ??= null;
        }
        target = targetList;
        targetKey = index;
      } else {
        if (targetKey is String) {
          targetKey = Uri.decodeQueryComponent(targetKey);
        }
        target[targetKey] ??= {};
        (target[targetKey] as Map)[keyName] ??= null;
        target = target[targetKey];
        targetKey = keyName;
      }
      restOfKey = contMatch[2];
    }
    target[targetKey] = nextValue();
  }
  return new Map.unmodifiable(map);
}