Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse query strings in Dart?

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.

like image 731
Tower Avatar asked Nov 28 '22 08:11

Tower


2 Answers

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.
like image 52
nunobaba Avatar answered Dec 05 '22 01:12

nunobaba


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.

like image 42
Kai Sellgren Avatar answered Dec 04 '22 23:12

Kai Sellgren