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

Dart出现‘int不是String子类型’错误,列表代码执行异常求助

解决Dart中“type 'int' is not a subtype of type 'String'”错误

这个错误的核心原因非常清晰:你试图把一个int类型的变量直接传给需要String类型的Text组件,类型不匹配的异常直接中断了itemBuilder的执行,所以你的print语句和后续代码都没机会运行。

咱们来拆解你的代码问题:

  • earthquake['properties']['time']返回的是Unix时间戳(整数,单位是秒),你把它乘以1000转成毫秒后,time仍然是int类型。
  • Text组件的title参数必须接收String类型的值,直接传int类型的time就触发了类型转换错误。
  • 你注释里的int.parse(time)是完全多余的操作——time本身已经是int了,这么写反而会引发新的错误。

修正后的代码

这里是修复后的itemBuilder部分,同时完整实现了时间格式化的功能:

itemBuilder: (BuildContext context, int index) {
  print("${earthquakes[index]}");
  var earthquake = earthquakes[index];
  // 显式声明time为int类型,避免隐式推断问题
  int time = earthquake['properties']['time'] as int;
  // 转成毫秒级时间戳,用于初始化DateTime
  int milliseconds = time * 1000;
  // 把时间格式化为可读字符串
  String formattedTime = DateFormat.yMMMMd().add_jm().format(DateTime.fromMillisecondsSinceEpoch(milliseconds));
  
  return ListTile(
    title: Text(formattedTime ?? "Empty"),
  );
}

关键修复点:

  • 明确类型声明:把time显式标记为int,避免隐式类型推断带来的不确定性。
  • 完成时间格式化:先用DateTime.fromMillisecondsSinceEpoch把毫秒级时间戳转成DateTime对象,再通过DateFormat把它格式化为字符串,确保传给Text的是合法的String类型。
  • 移除错误操作:删掉多余的int.parse(time),避免无效的类型转换。

另外,建议你在访问earthquakes[0]之前做个空值检查,防止数组越界:

if (earthquakes.isNotEmpty) {
  // 处理第一个地震数据的逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:43:13