Last active
August 24, 2022 20:22
-
-
Save danielgomezrico/f0af61d40f37360e051e7bedde273541 to your computer and use it in GitHub Desktop.
Dart - how to create a url with query params with language features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use language features to build the url | |
String buildUrlWithQueryParams(String url, Map<String, dynamic> queryParams) { | |
final uri = Uri.parse(url); | |
final fullUri = uri.replace( | |
queryParameters: { | |
...uri.queryParameters, | |
...queryParams, | |
}, | |
); | |
final parsedUrl = fullUri.toString(); | |
if (parsedUrl[parsedUrl.length - 1] == '?') { | |
return parsedUrl.substring(0, parsedUrl.length - 1); | |
} else { | |
return parsedUrl; | |
} | |
} | |
void main() { | |
final url = buildUrlWithQueryParams("www.google.com?name=ok%C3%BCn-living-cancun", {'param': 'value'}); | |
print(url); // www.google.com?name=ok%C3%BCn-living-cancun¶m=value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment