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

Dart/Flutter报错Future<dynamic>不是ProductModel子类型怎么解决?

问题根因

你的报错由两个核心错误共同导致:

  1. Dart中所有async修饰的方法,返回值必须是Future类型。你没有给GetProduct方法明确声明返回的Future包裹类型,且调用时未加await获取异步执行结果,导致直接拿到了Future<dynamic>类型对象,和需要的ProductModel类型不匹配。
  2. 你的GetProduct方法实际返回的是List<ProductModel>类型的商品列表,但你调用时用了List.add()方法(该方法用于添加单个元素),类型逻辑本身也不匹配。
修复步骤

1. 修正Api类的GetProduct方法签名

明确声明异步返回类型,修改后的方法签名如下,方法内部原有逻辑保持不变:

// 增加Future包裹返回的列表类型
Future<List<ProductModel>> GetProduct() async {
  // 原有逻辑不用改
  String BasicUrl = "my link";
  var headers = {
    'Authorization': 'some thing',
  };
  final url = Uri.parse('${BasicUrl}products');

  http.Response ProResponse = await http.get(url, headers: headers);
  ProResponse.headers.addAll(headers);
  List<ProductModel> items2 = [];
  if (ProResponse.statusCode == 200) {
      var decoded = (jsonDecode(ProResponse.body));
      if (decoded.length == 0) {
        print("null2");
      } else {
        for (var i in decoded) {
          var images = (i["images"][0]["src"]);
          var id = (i["id"]);
          var description = (i["description"]);
          var price = (i["price"]);
          var regularprice = (i["regular_price"]);
          var name = (i["name"]);

          var productItem = ProductModel(
              images: images ??=
              "a link",
              name: name,
              description: description,
              price: price ?? "",
              regular_price: regularprice ?? "",
              id: id);
          items2.add(productItem);
        }
      }
      return items2;
  } else {
    print(ProResponse.reasonPhrase);
    return items2;
  }
}

2. 修正FetchItems2方法的调用逻辑

增加await获取异步返回的商品列表,改用addAll方法批量添加列表元素,修改后代码如下:

List<ProductModel> items2 = [];
FetchItems2() async {
  Api ap1 = Api();
  // 等待异步方法执行完成拿到列表结果
  final productList = await ap1.GetProduct();
  // 批量添加列表元素
  items2.addAll(productList);
}
注意事项

调用FetchItems2方法的位置也需要添加await修饰,避免出现页面加载完成但商品数据还未请求完毕的空数据问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:15:06