66

Is there a function to do urlencoding in Dart? I am doing a AJAX call using XMLHttpRequest object and I need the url to be url encoded.

I did a search on dartlang.org, but it didn't turn up any results.

Sudar
  • 18,954
  • 30
  • 85
  • 131

8 Answers8

88
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');

var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);

http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri

gines capote
  • 1,110
  • 1
  • 8
  • 12
39

Update: There is now support for encode/decode URI in the Dart Uri class

Dart's URI code is placed in a separate library called dart:uri (so it can be shared between both dart:html and dart:io). It looks like it currently does not include a urlencode function so your best alternative, for now, is probably to use this Dart implementation of JavaScript's encodeUriComponent.

Riz-waan
  • 603
  • 3
  • 13
Lars Tackmann
  • 20,275
  • 13
  • 66
  • 83
29
Uri.encodeComponent(url); // To encode url
Uri.decodeComponent(encodedUrl); // To decode url
Thanthu
  • 4,399
  • 34
  • 43
27

I wrote this small function to convert a Map into a URL encoded string, which may be what you're looking for.

String encodeMap(Map data) {
  return data.keys.map((key) => "${Uri.encodeComponent(key)}=${Uri.encodeComponent(data[key])}").join("&");
}
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
3

I dont' think there is yet. Check out http://unpythonic.blogspot.com/2011/11/oauth20-and-jsonp-with-dartin-web.html and the encodeComponent method.

Note, it's lacking some characters too, it needs to be expanded. Dart really should have this built in and easy to get to. It may have it in fact, but I didn't find it.

Douglas Fils
  • 311
  • 4
  • 14
0

Safe Url Encoding in flutter
Ex.

String url  = 'http://example.org/';
String postDataKey = "requestParam="
String postData = 'hdfhghdf+fdfbjdfjjndf'

In Case of get request :

Uri.encodeComponent(url+postDataKey+postData);

In Case of Post Data Request use flutter_inappwebview library

var data = postDataKey + Uri.encodeComponent(postData);
webViewController.postUrl(url: Uri.parse(url), postData: utf8.encode(data));
0

Uri.encodeComponent() is correct, Uri.encodeFull() has a bug, see below example:

void main() {
  print('$text\n');
  var coded = Uri.encodeFull(text);
  print(coded);
  print('\n');
  coded = Uri.encodeComponent(text);
  print(coded);
  
}

var text = '#2020-02-29T142022Z_1523651918_RC2EAF9OOHDB_RT.jpg';
    
John
  • 1
  • 1
0

This solution worked for me well. Build an Uri, pass the Map onto the queryParameters. Get the encoded data by

Uri(queryParameters: <Map data>).query;

eg:

Uri(queryParameters: {'key1': val1, 'key2': val2}).query;
Ron Bis
  • 25
  • 2
  • 8