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

Flutter接口响应JSON映射到Dart模型类报错如何解决?

问题原因
  • 你调用的接口返回的JSON根结构是对象,不是数组,强行把json.decode(response.body)强转成List会直接抛出类型不匹配异常。
  • 你生成的Advertisement模型已经对应了整个根JSON结构(包含items、total、pageNumber三个字段),不需要套一层List。
  • 你需要的广告列表是Advertisement实例下的items属性,不需要把整个响应转成List<Advertisement>。
修复步骤

首先修改fetchAdvertisements方法,直接将响应转成Advertisement对象,返回你需要的广告条目列表即可:

Future<List<Items>?> fetchAdvertisements() async {
  var response = await HttpActions.makeHttpGet(
      {},
      AppConstants.ADVERTISEMENTS_ENDPOINT,
      {HttpHeaders.contentTypeHeader: HttpActions.APPLICATION_JSON_HEADER});

  print(response.statusCode);
  if (response.statusCode == 200) {
    final responseJson = json.decode(response.body);
    // 整个响应直接转Advertisement对象
    Advertisement adResult = Advertisement.fromJson(responseJson);
    // 返回广告条目列表
    return adResult.items;
  } else {
    throw Exception('Failed to load post');
  }
}

接下来修改页面渲染逻辑,用ListView实现滚动展示,注意Column内嵌套ListView需要套Expanded避免布局溢出:

@override
Widget build(BuildContext context) => Scaffold(
  body: Scaffold(
    backgroundColor: const Color(0xFEF9F9FC),
    floatingActionButtonLocation:
        FloatingActionButtonLocation.centerDocked,
    floatingActionButton: buildFAB(),
    bottomNavigationBar: BuildBottomAppBar(),
    body: Container(
      padding: EdgeInsets.all(35.0),
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: Column(
        children: [
          Expanded(
            child: FutureBuilder<List<Items>?>(
              future: fetchAdvertisements(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (snapshot.hasError) {
                  return Center(child: Text("An error occurred: ${snapshot.error}"));
                }
                if (!snapshot.hasData || snapshot.data!.isEmpty) {
                  return const Center(child: Text("暂无广告数据"));
                }
                // 渲染滚动列表
                return ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) {
                    final item = snapshot.data![index];
                    return ListTile(
                      leading: item.imageUrl?.isEmpty ?? true 
                          ? const Icon(Icons.broken_image) 
                          : Image.network(item.imageUrl!),
                      title: Text(item.title ?? ""),
                      subtitle: Text(item.city ?? ""),
                    );
                  },
                );
              },
            ),
          )
        ],
      ),
    ),
  ),
);
可选优化
  • 插件生成的模型用了私有属性+getter的冗余写法,如果你使用空安全版本的Dart,可以改成不可变数据类写法,减少冗余代码。
  • 接口请求成功后不要返回null,正常返回对应数据即可,减少后续空判断的逻辑复杂度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 19:42:02