buildURLWithQueryParameters function

String buildURLWithQueryParameters(
  1. String url,
  2. Map<String, String?> parameters, {
  3. bool removeFragment = false,
})

Builds an URL with Query parameters adding the map parameters to current Query parameters.

removeFragment If true will remove URL fragment.

Implementation

String buildURLWithQueryParameters(String url, Map<String, String?> parameters,
    {bool removeFragment = false}) {
  if (parameters.isEmpty) return url;

  var uri = Uri.parse(url);

  Map<String, String?> queryParameters;

  if (uri.query.isEmpty) {
    queryParameters = Map<String, String?>.from(parameters);
  } else {
    queryParameters = uri.queryParameters;
    queryParameters = Map<String, String?>.from(queryParameters);
    queryParameters.addAll(parameters);
  }

  String? fragment = uri.fragment;
  if (removeFragment || fragment.isEmpty) {
    fragment = null;
  }

  return Uri(
          scheme: uri.scheme,
          userInfo: uri.userInfo,
          host: uri.host,
          port: uri.port,
          path: Uri.decodeComponent(uri.path),
          queryParameters: queryParameters,
          fragment: fragment)
      .toString();
}