相关文章推荐
温暖的火腿肠  ·  WPF ...·  2 年前    · 
酷酷的枕头  ·  Java方程解_Rich ...·  2 年前    · 
深沉的凉茶  ·  java.lang.NoClassDefFo ...·  2 年前    · 

Empty vs. null query parameters - wrong encoding in Uri #56036

@jakobleck

Description

Insert the following code in the dartpad (tested with Dart 3.4.3, Flutter 3.22.2 stable):

void main() {
  final uri = Uri(
    scheme: 'http',
    host: 'google.com',
    port: 80,
    path: '',
    queryParameters: {"test1": null, "test2": ""},
  print(uri.toString());
  final parsedUri = Uri.parse(uri.toString());
  print(parsedUri.queryParameters);
  print(parsedUri.queryParameters["test1"] == null);
  print(parsedUri.queryParameters["test1"] == "");
  print(parsedUri.queryParameters["test2"] == null);
  print(parsedUri.queryParameters["test2"] == "");

The result is:

http://google.com?test1&test2
{test1: , test2: }
false
false

i.e. it seems that dart is treating empty and null values the same way when creating the query string, thus making it impossible to later discern which was which.
I stumbled upon this problem when developping a Java Spring backend which would accept ...?test2or ...?test1=null&... as test1 being null, whereas ...?test1&test2 or ...?test1=&test2 is treated as test1 being an empty string, which seems reasonable. I'm not saying that the dart code needs to be consistent with that - although this would be convenient - but that at least dart should be consistent when encoding, i.e. allowing to correctly recover what was encoded in the Uri. In fact the convention parsed by the Spring backend seems to be the same as parsed by Uri.parse, cf.:

void main() {
  final uri = Uri.parse("http://google.com?test2&test3=&test4=null");
  print("-${uri.queryParameters["test1"]}-");
  print("-${uri.queryParameters["test2"]}-");
  print("-${uri.queryParameters["test3"]}-");
  print("-${uri.queryParameters["test4"]}-");

which yields

-null-
-null-