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

Flutter中如何在URL中传递参数实现接口请求

Flutter 路径参数传参实现方案

该接口使用的是路径参数(Path Parameters),参数需要直接嵌入URL路径中,服务端会从路径段中解析对应值,不会读取请求体(Body)中的内容,因此把参数放在Body中无法被接口识别。


实现步骤

1. 依赖引入

首先确保在pubspec.yaml中添加了网络请求依赖,以常用的http包为例:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0 # 可替换为最新版本

2. 构造请求URI

推荐用Flutter自带的Uri类构造URL,会自动处理参数编码,避免特殊字符导致的URL格式错误:

import 'package:http/http.dart' as http;

Future<void> requestFareData() async {
  // 定义需要传递的参数
  final int source = 1;
  final int destination = 17;
  final int fare = 2;
  final String type = "SJT";

  // 构造完整请求URI
  final Uri requestUri = Uri(
    scheme: 'http',
    host: 'localhost',
    port: 9000,
    pathSegments: [
      'api',
      'bmrc',
      'fare',
      source.toString(),
      destination.toString(),
      fare.toString(),
      type
    ],
  );

  // 调试用:打印构造好的URL,确认和Postman测试地址一致
  print('请求地址:${requestUri.toString()}');

  try {
    // 发送GET请求(如果接口要求其他请求方式,替换为对应的post/put等即可)
    final http.Response response = await http.get(requestUri);

    if (response.statusCode == 200) {
      // 请求成功,处理返回数据
      print('接口返回数据:${response.body}');
    } else {
      // 处理接口错误
      print('请求失败,状态码:${response.statusCode},错误信息:${response.body}');
    }
  } catch (e) {
    // 处理网络异常
    print('请求发生异常:$e');
  }
}

注意事项

  • 若接口要求POST/PUT等请求方式,仅需将http.get替换为对应方法即可,参数依然放在构造的URI中,无需写入请求体,除非接口额外要求请求体携带其他参数。
  • 若参数值包含中文、空格、特殊符号,不要直接用字符串插值拼接URL,使用Uri类构造可自动完成编码,也可以手动调用Uri.encodeComponent(参数值)对每个参数单独编码。
  • 出现问题优先打印构造好的requestUri.toString(),和Postman测试通过的地址对比,先排除参数拼接错误的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:15:06