encodingdarturiencoding

How do I url-encode in Dart in the format that the Twitter API expects?


I wrote some code to post tweets in C#. One of the things that tripped me up was the url-encoding of data since there seemed to be many options:

var input = "Hello Ladies + Gentlemen, a signed OAuth request!";
var expected = "Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21";

Console.WriteLine(WebUtility.UrlEncode(input) == expected); // False
Console.WriteLine(Uri.EscapeUriString(input) == expected); // False
Console.WriteLine(Uri.EscapeDataString(input) == expected); // True

I'm now trying to do the same thing in Dart. I've tried all the encode methods in the Uri class, but none seem to output the same.

Code: (DartPad)

print(Uri.encodeQueryComponent("Hello Ladies + Gentlemen, a signed OAuth request!"));
print(Uri.encodeFull("Hello Ladies + Gentlemen, a signed OAuth request!"));
print(Uri.encodeComponent("Hello Ladies + Gentlemen, a signed OAuth request!"));

Output:

Hello+Ladies+%2B+Gentlemen%2C+a+signed+OAuth+request%21
Hello%20Ladies%20+%20Gentlemen,%20a%20signed%20OAuth%20request!
Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request!

The last one (encodeComponent) seems the closest, just the exclamation mark is wrong.

Is there an existing method that does this encoding as I require (the same as C#'s EscapeDataString)?


Solution

  • The convert package works perfectly. There was previously a bug causing numbers to be encoded but a fix was merged and released today in 2.0.1.