Flutter http.get 存在路径参数问题

Gov*_*iyo 5 dart flutter

如果我尝试在 Postman 上运行,它会完美运行。看下图。

在此输入图像描述

你可以看到,下面是url

https://xx.yy/api/user/:slug

路径参数为

蛞蝓

我在 Flutter 中的代码不起作用!

    final _authority = "xx.yy";
    final _path = "api/user/:slug"; // Tried to replace "api/user/slug" AND "api/user"
    final _params = { "slug" : "govadiyo" };
    final _uri =  Uri.https(_authority, _path, _params);

    print(Uri.encodeFull(_uri.toString()));
    var response = await http.get(Uri.encodeFull(_uri.toString()), headers: {'Content-Type': 'application/json'});
    print(response.body);
Run Code Online (Sandbox Code Playgroud)

上面的代码有什么问题吗?

Les*_*iak 6

正如您正确注意到的那样,您需要一个路径变量,而不是查询参数(这意味着您的变量成为 url 的一部分)。

您可以使用字符串插值将变量放入 url 中(事实上,串联也可以)。该变量可能包含需要编码的字符。

final slug = 'govadiyo';
final url = Uri.encodeFull('api/user/${slug}');
print(url);
Run Code Online (Sandbox Code Playgroud)