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

Flutter调用REST API报'list<dynamic>' is not a subtype of type 'string'错误求解决

错误原因
  • 报错'List<dynamic>' is not a subtype of type 'String'的核心问题出在JSON解析步骤:你直接把未经解码的字符串类型response.body传给了petaniFromJson方法,而该方法内部要么是预期接收已经解码后的JSON数组,要么解析逻辑错误,把解码生成的List<dynamic>类型当成了String类型处理。
修复方案

1. 调整接口请求的解析逻辑

首先导入JSON解析依赖,然后先对响应内容做解码,再遍历转为Petani对象数组,修改后的getDafPet方法如下:

import 'dart:convert';

Future<List<Petani>> getDafPet() async {
  final response = await client.get("http://10.0.2.2:8000/api/dafPetani");
  if (response.statusCode == 200) {
    // 先将字符串类型的响应体解码为JSON数组
    final List<dynamic> jsonList = jsonDecode(response.body);
    // 遍历数组元素,逐个转为Petani对象
    return jsonList.map((jsonItem) => Petani.fromJson(jsonItem)).toList();
  } else {
    return []; // 建议返回空数组代替null,减少后续判空逻辑
  }
}

2. 确认Petani模型类的解析方法正确

确保你的Petani类的fromJson工厂方法是接收Map<String, dynamic>类型入参的,示例如下:

class Petani {
  final String idUser;
  final String nama;
  // 其余字段自行补充

  Petani({required this.idUser, required this.nama});

  factory Petani.fromJson(Map<String, dynamic> json) {
    return Petani(
      idUser: json['ID_User'] as String,
      nama: json['nama'] as String,
      // 其余字段对应JSON的key依次赋值即可
    );
  }
}

3. 优化FutureBuilder的空判断逻辑

补全加载状态、增加空值兼容,避免空指针异常:

FutureBuilder(
  future: ApiServices().getDafPet(),
  builder: (BuildContext context, AsyncSnapshot<List<Petani>> snapshot){
    if(snapshot.hasError){
      return Center(
        child: Text(
          "Something wrong with message : ${snapshot.error.toString()}",
          style: TextStyle(
            color: Color(0xFFAB47BC),
          ),
          textAlign: TextAlign.center,
        ),
      );
    }else if(snapshot.connectionState == ConnectionState.done){
      // 空值兼容,赋值为空数组
      lptn = snapshot.data ?? [];
      return ListView.builder(
        itemBuilder: (context, position){
          return Card(
            margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
            shadowColor: Color(0xFFBA68C8),
            elevation: 2.0,
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              padding: EdgeInsets.fromLTRB(5, 2.5, 5, 2.5),
              margin: EdgeInsets.fromLTRB(2.5, 2.5, 2.5, 2.5),
              child: ListTile(
                title: Text(
                  lptn[position].nama,
                  style: TextStyle(
                    color: Color(0xFFAB47BC),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                subtitle: Text(
                  lptn[position].nama,
                  style: TextStyle(
                    color: Colors.black54,
                    fontSize: 13,
                  ),
                ),
                trailing: IconButton(
                  icon: Icon(
                    Icons.arrow_forward_ios_rounded,
                    color: Colors.black26,
                    size: 20,
                  ),
                  onPressed: (){
                    // 跳转逻辑自行补充
                  },
                ),
              ),
            ),
          );
        },
        itemCount: lptn.length,
      );
    }
    // 补全加载中状态的UI
    else {
      return Center(child: CircularProgressIndicator(color: Color(0xFFAB47BC),));
    }
  }
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:57:03