skip to Main Content

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)?

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. I can’t find a Dart function that is equivalent to C#’s EscapeDataString, however I think I was able to implement one. Feel free to try it and see if you find any issues.

    See this Dartpad:
    https://dartpad.dartlang.org/4336dad4dc0603952a7c2e545cb8726c

    It’s based on the fact that the Dart docs says:

    All characters except uppercase and lowercase letters, digits and the characters -_.!~*'() are percent-encoded.

    So the functions I provided adds percent encoding of those specific characters.

    As I understand it from the C# docs on EscapeDataString it does encode these characters by default whereas no Dart function I could find does that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search