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

Dart调用外部传入二维列表的shape属性报NoSuchMethodError如何解决

问题原因

Dart 原生的 List 类型本身没有内置 shape 属性,你能调用这个属性是项目中引入了针对 List 类型的扩展方法(Extension)。而Dart的扩展方法属于静态分派,是否能调用只取决于变量的静态编译时类型,和运行时的实际类型无关。
你代码里的两个变量存在关键类型差异:

  • 函数内部定义的 list 明确声明了静态类型为 List<List<int>>,编译时就能匹配到对应的 shape 扩展 getter,调用正常。
  • testFunc 的入参 image 没有声明类型,默认静态类型为 dynamic,编译器不会为 dynamic 类型匹配扩展方法,运行时会直接在原生 List 的实现里找 shape 属性,自然就会报错找不到。

修复方案

最简单的修复是给函数参数加上明确的类型标注:

// 给image参数添加类型声明
void testFunc(List<List<int>> image) {
  List<List<int>> list = [
    [0, 10, 10, 0],
    [20, 30, 30, 20],
    [10, 20, 20, 10],
    [0, 5, 5, 0]
  ];

  print(list.shape[0]);
  // 现在调用正常
  print(image.shape[0]);
}

如果出于业务需要必须使用无类型的参数,也可以在调用时手动做类型转换:

print((image as List<List<int>>).shape[0]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:15:04