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

Flutter/Dart中如何将HTTP响应在新页面通过ListView展示

Flutter 接口返回列表跳转新页面用ListView渲染实现方案

现有代码问题点

  • 路由跳转时没有把接口拿到的message数据传给目标页面,直接传了固定的const DashboardPage(),页面拿不到要渲染的数据
  • 返回的列表最后一位是无关数字473,不属于要展示的提示文本,需要提前过滤
  • 目标页面没有实现列表渲染逻辑

具体实现代码

1. 修改接口请求后的逻辑,处理数据并传参跳转

把原有请求后的代码替换为以下内容:

var response = await http.get(
  Uri.parse(
      'http://192.168.1.8:8080/HongLeong/MENU_REQUEST.do?_dc=1657717579436&table_id=25018&id_MenuAction=3&reset_context=1&ViewType=MENU_REQUEST&gui_open_popup=1&id_Window=5&activeWindowId=mw_5&noOrigUserDate=true&LocalDate=20220713&LocalTime=21061900&TimeZone=Asia/Shanghai&UserDate=0&UserTime=0&server_name=OPRISK_DATACOLLECTOR&key_id_list=&cell_context_id=0&id_Desktop=100237&operation_key=1000007&operation_sub_num=-1&is_json=1&is_popup=0&is_search_window=0&ccsfw_conf_by_user=0&is_batch=0&previousToken=1657717554097&historyToken=1657717579434&historyUrl=1'),
  headers: {HttpHeaders.cookieHeader: cookies},
);

ResponseModel responseModel = ResponseModel.fromJson(jsonDecode(response.body));

// 提取字段值,过滤掉非提示类的无效内容
List<String> messageList = responseModel.response.genericListAnswer.listNode
    .map((x) => x.toJson()['field'][0]['field_value'].toString())
    .where((element) => element.startsWith('There are')) // 可根据业务规则调整过滤条件
    .toList();

// 跳转时将处理好的列表传入目标页面,不要传固定const常量
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => DashboardPage(messageList: messageList)),
);

2. 改造DashboardPage,接收参数并实现ListView渲染

class DashboardPage extends StatelessWidget {
  // 定义入参变量接收列表数据
  final List<String> messageList;
  const DashboardPage({super.key, required this.messageList});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('消息列表')),
      // 用ListView.builder按需渲染,长列表场景性能更优
      body: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: messageList.length,
        itemBuilder: (context, index) {
          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Text(
                messageList[index],
                style: const TextStyle(fontSize: 14),
              ),
            ),
          );
        },
      ),
    );
  }
}

可选优化

  • 如果需要去除重复数据(当前示例返回存在多条重复提示),可以在toList()前追加.toSet().toList()即可自动去重
  • 如果不想写死文本过滤规则,也可以通过判断元素类型过滤非字符串内容,适配后续接口变动
  • 列表项样式可根据业务需求替换为ListTile、自定义组件等,上述代码仅为基础实现示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 18:54:24