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

Flutter DataTable组件报Dynamic call of null错误,求排查解决

错误原因与解决方案

你触发“Dynamic call of null”错误的核心原因是把Currency实体类对象当成了Map来访问。你的Currency是普通自定义类,没有实现Map的索引操作符[],执行row[column]时,相当于对不支持该操作的对象调用了不存在的方法,最终抛出空指针相关错误。

看你的代码逻辑:

  • 主类定义的Currency是包含currencyName、buyingPrice、sellingPrice三个属性的实体类
  • 但在DataTable的cells生成逻辑里,你用了row[column]这种仅Map类型支持的访问方式,这在普通类上完全不兼容。

解决方案一:匹配字段名获取属性值

修改DataRow的cells生成逻辑,根据column的字符串值对应获取Currency对象的属性:

DataTable(
  dividerThickness: Cl.dp0,
  dataRowMaxHeight: Cl.dp40,
  dataRowMinHeight: Cl.dp8,
  headingRowHeight: Cl.dp40,
  headingRowColor: MaterialStateColor.resolveWith(
      (states) => ClColors.secondary10),
  headingTextStyle: ClTypography.normal2SemiBold
      .copyWith(color: ClColors.primary20),
  dataTextStyle:
      ClTypography.normal2SemiBold.copyWith(color: ClColors.dark20),
  columns: widget.tableColumn!.map((element) {
    return DataColumn(label: Text(element));
  }).toList(),
  rows: widget.currencyList!.map((row) {
    return DataRow(
      cells: widget.tableColumn!.map((column) {
        String cellValue;
        // 根据字段名匹配对应属性
        switch(column) {
          case 'currency':
            cellValue = row.currencyName;
            break;
          case 'buy':
            cellValue = row.buyingPrice;
            break;
          case 'sell':
            cellValue = row.sellingPrice;
            break;
          default:
            cellValue = ''; // 处理未知字段的默认值
        }
        return DataCell(Text(cellValue));
      }).toList(),
    );
  }).toList(),
),

解决方案二:给Currency类添加索引操作符

如果希望保留row[column]的写法,可以给Currency类实现Map风格的索引操作符:

class Currency {
  String currencyName, buyingPrice, sellingPrice;
  Currency(
    this.currencyName,
    this.buyingPrice,
    this.sellingPrice,
  );

  // 添加索引操作符,支持row['currency']的访问方式
  String? operator [](String key) {
    switch(key) {
      case 'currency':
        return currencyName;
      case 'buy':
        return buyingPrice;
      case 'sell':
        return sellingPrice;
      default:
        return null;
    }
  }
}

这样原来的row[column]!写法就能正常工作,注意处理默认返回null的情况,避免空指针风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:45:05