6

How do I parse query strings safely in Dart?

Let's assume I have q string with the value of:

?page=main&action=front&sid=h985jg9034gj498g859gh495

Ideally the code should work both in the server and client, but for now I'll settle for a working client-side code.

4 Answers 4

19

The simpler, the better. Look for the splitQueryString static method of the Uri class.

Map<String, String> splitQueryString(
    String query, {
    Encoding encoding = utf8,
})

Splits the query into a map according to the rules specified for FORM post in the HTML 4.01 specification section 17.13.4.

Each key and value in the returned map has been decoded. If the query is the empty string, an empty map is returned.

Keys in the query string that have no value are mapped to the empty string.

Sign up to request clarification or add additional context in comments.

Comments

7

I have made a simple package for that purpose exactly: https://github.com/kaisellgren/QueryString

Example:

import 'package:query_string/query_string.dart');

void main() {
  var q = '?page=main&action=front&sid=h985jg9034gj498g859gh495&enc=+Hello%20&empty';

  var r = QueryString.parse(q);

  print(r['page']); // "main"
  print(r['asdasd']); // null
}

The result is a Map. Accessing parameters is just a simple r['action'] and accessing a non-existant query parameter is null.

Now, to install, add to your pubspec.yaml as a dependency:

dependencies:
  query_string: any

And run pub install.

The library also handles decoding of things like %20 and +, and works even for empty parameters.

It does not support "array style parameters", because they are not part of the RFC 3986 specification.

1 Comment

10 yo solution, unfortunately the dependency is deprecated.
2

all of the answers are pretty much outdated.

Quickest and easiest way:

Uri uri = Uri(query: data);

var queryParameters = uri.queryParameters;

var myValue = queryParameters["my_value"];

Comments

-1

I done that just like this:

 Map<String, String> splitQueryString(String query) {
    return query.split("&").fold({}, (map, element) {
      int index = element.indexOf("=");
      if (index == -1) {
        if (element != "") {
          map[element] = "";
        }
      } else if (index != 0) {
        var key = element.substring(0, index);
        var value = element.substring(index + 1);
        map[key] = value;
      }
      return map;
    });
 }

I took it from splitQueryString

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.