Reputation: 102905
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.
Upvotes: 6
Views: 4211
Reputation: 1760
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"];
Upvotes: 2
Reputation: 201
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
Upvotes: 0
Reputation: 524
The simpler, the better. Look for the splitQueryString static method of class Uri.
Map<String, String> splitQueryString(String query, {Encoding encoding: UTF8})
Returns the query split 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.
Upvotes: 18
Reputation: 30292
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.
Upvotes: 7