Alex
Alex

Reputation: 8493

Extract parameter / value pairs from an Uri as a Map

How do I get the parameter / value pairs of an URL / URI using Dart? Unfortunately currently there is no built-in functionality for this problem neither in the Uri library or the Location interface.

Upvotes: 6

Views: 1335

Answers (4)

Mark E. Haase
Mark E. Haase

Reputation: 26911

There is now a queryParameters member of Uri that returns a Map

Uri u = Uri.parse("http://app.org/main?foo=bar&baz=bat");
Map<String,String> qp = u.queryParameters;
print(qp);

// {foo: bar, baz: bat}

Upvotes: 2

Alex
Alex

Reputation: 8493

  Map<String, String> getUriParams(String uriSearch) {
    if (uriSearch != '') {
      final List<String> paramValuePairs = uriSearch.substring(1).split('&');

      var paramMapping = new HashMap<String, String>();
      paramValuePairs.forEach((e) {
        if (e.contains('=')) {
          final paramValue = e.split('=');
          paramMapping[paramValue[0]] = paramValue[1];
        } else {
          paramMapping[e] = '';
        }
      });
      return paramMapping;
    }
  }

// Uri: http://localhost:8080/incubator/main.html?param=value&param1&param2=value2&param3
  final uriSearch = window.location.search;
  final paramMapping = getUriParams(uriSearch);

Upvotes: 0

Roger Chan
Roger Chan

Reputation: 1413

 // url=http://127.0.0.1:3030/path/Sandbox.html?paramA=1&parmB=2#myhash
void main() {
   String querystring = window.location.search.replaceFirst("?", "");
   List<String> list = querystring.split("&").forEach((e) => e.split("="));
   print(list); // [[paramA, 1], [parmB, 2]]
}

Upvotes: 0

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76273

You can use Uri.splitQueryString to split the query into a map.

Upvotes: 3

Related Questions