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

Flutter报错:参数类型'String'无法赋值给'int'参数,如何修复?

修复状态文本转换的类型不匹配错误

错误原因很明确:getStatusText()方法要求传入int类型的参数,但你调用时传了problem.status.toString()生成的String类型值,导致类型不匹配。根据problem.status的实际类型,有两种修复方式:


方式1:如果problem.status本身是int类型

直接移除.toString(),传入原始的int值即可:

subtitle: Text(
  getStatusText(problem.status),
  style: TextStyle(
      fontWeight: FontWeight.bold, fontSize: 17),
),

方式2:如果problem.status是String类型(数据库返回字符串格式的数字)

需要先将字符串转换为int,推荐用int.tryParse()做安全转换(避免转换失败导致崩溃):

subtitle: Text(
  getStatusText(int.tryParse(problem.status) ?? -1),
  style: TextStyle(
      fontWeight: FontWeight.bold, fontSize: 17),
),

这里用?? -1处理转换失败的情况,确保总有合法的int传入方法,此时getStatusText的default分支会返回UnRecognised。


额外优化建议

在模型层就把状态字段定义为int类型,减少后续类型转换的麻烦。比如修改problemModel:

class problemModel {
  // 其他字段...
  int status;

  problemModel({required this.status, /* 其他参数 */});

  // 从数据库/JSON映射时直接转为int
  factory problemModel.fromJson(Map<String, dynamic> json) {
    return problemModel(
      status: json['status'] is String ? int.parse(json['status']) : json['status'],
      // 其他字段处理...
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:29:52