【问题标题】:The operator '+' isn't defined for the type 'Uri'未为“Uri”类型定义运算符“+”
【发布时间】:2021-03-23 08:35:22
【问题描述】:

我有一个项目,我使用 http 包发出各种 http 请求。我最近更新了包,我无法将 url 链接附加到我拥有的基本 url 的末尾。这是示例代码

  var _url = Uri.parse('url here');

  var token;

  _getToken() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    token = jsonDecode(localStorage.getString('token'))['token'];
  }

  authData(data, apiUrl) async {
    try {
      var fullUrl = _url +  apiUrl;
      return await http.post(fullUrl,
          body: jsonEncode(data), headers: _setHeaders());
    } catch (e) {
      print(e);
    }
  }

这是它显示的错误

The operator '+' isn't defined for the type 'Uri'.
Try defining the operator '+'.dartundefined_operator

错误发生在var fullUrl = _url + apiUrl;,特别是 + 运算符。在更新之前它运行良好但是我找不到它的解决方案

【问题讨论】:

    标签: flutter dart flutter-http dart-http


    【解决方案1】:

    以这种方式使用它,首先组合您的字符串,然后解析您的 Uri。 Uri class\object 不是可以使用 + 连接字符串的字符串。执行以下操作:

    String _urlBase = 'http://192.168.1.236/connect/api/v1';
    

    保持 getToken() 函数不变,然后使用它:

    authData(data, apiUrl) async {
    try {
      String _finalUrl = _urlBase + apiUrl;
      Uri _uri = Uri.parse(_finalUrl);
      return await http.post(_uri,
          body: jsonEncode(data), headers: _setHeaders());
    } catch (e) {
      print(e);
    }
    }
    

    这应该可以解决您的问题。

    【讨论】:

      【解决方案2】:

      我使用带有字符串 url 的 http.post 试试这个

      var _url = 'http://192.168.1.236/connect/api/v1';
      

      【讨论】:

      • 我不明白
      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 2021-06-11
      • 2020-10-10
      • 2020-12-09
      • 1970-01-01
      • 2022-01-05
      • 2021-10-01
      • 2021-01-29
      相关资源
      最近更新 更多