aknd
aknd

Reputation: 843

flutter dart add convert a query string to a map

Trying to add the params query string to the queryParameters map.

_params = "from=2021-04-10&to=2021-05-20";
// or like
_params = "var1=abc&var2=123";


Map<String, dynamic> queryParameters = {
  'token': _token.toString(),
  'page': _page.toString(),
};

final response = await http.get(
  Uri.https('www.domain.com', 'api/visits/index.json', queryParameters),
  headers: {"Content-Type": "application/json"},
);

Should be:

Map<String, dynamic> queryParameters = {
  'token': _token.toString(),
  'domain_id': domain.id.toString(),
  'from': '2021-04-10',
  'to': '2021-05-20',
  // .... any variable from _params...
};

Upvotes: 2

Views: 1168

Answers (2)

jamesdlin
jamesdlin

Reputation: 90115

If you already have an encoded query string:

var _params = "from=2021-04-10&to=2021-05-20";

and are trying to parse it into a Map<String, String>, then you can use Uri.splitQueryString:

var parsedQueryParameters = Uri.splitQueryString(_params);

Unlike manually parsing by tokenizing on & and = characters, Uri.splitQueryString also will decode escaped characters.

If you need to merge that into an existing Map<String, String> of query parameters, then you can use Map.addAll:

queryParameters.addAll(Uri.splitQueryString(_params));

Upvotes: 3

Nisanth Reddy
Nisanth Reddy

Reputation: 6420

One way to do this would be to split your queryString

String params = 'from=2021-04-10&to=2021-05-20';

Map<String, dynamic> queryParameters = {
  'token': _token.toString(),
  'page': _page.toString(),
};

params.split("&").forEach((item) { // Split with & first to get each key value pair
  var param = item.split('=');  // Split with = to get the key and value
  queryParameters[param[0]] = param[1];
});

Upvotes: 1

Related Questions