You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter http.get报错:String类型无法赋值给Uri类型参数

报错原因

Flutter 生态中常用的http网络请求库从0.13.0版本开始调整了接口参数类型:所有网络请求方法(get/post/put/delete等)不再支持直接传入字符串格式的URL,强制要求传入Uri类型的URI实例作为请求地址参数。代码中直接将String类型的url变量传入http.get方法,就会触发该类型不匹配报错。

修复方法

使用Dart内置的Uri.parse()方法,将拼接好的字符串URL解析为Uri类型对象后再传入请求方法即可,修复后的代码如下:

void _search(String query){
    String url = "https://api.github.com/search/users?q=${query}&per_page=20&page=0";
    // 核心改动:将字符串URL解析为Uri类型
    http.get(Uri.parse(url))
        .then((response){
          print(response);
    })
    .catchError((err){
      print(err);
    });
  }

优化提示:不建议手动拼接URL查询参数,容易因特殊字符未转义导致请求异常,可以通过Uri的构造函数自动处理参数拼接与转义,写法更稳妥:

void _search(String query){
  Uri requestUri = Uri(
    scheme: 'https',
    host: 'api.github.com',
    path: '/search/users',
    queryParameters: {
      'q': query,
      'per_page': '20',
      'page': '0'
    }
  );
  http.get(requestUri)
    .then((response) => print(response))
    .catchError((err) => print(err));
}

内容的提问来源于stack exchange,提问作者Nzashi Jeanluc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 12:39:15