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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With