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

Flutter类型转换异常:String无法转为int?问题求助

问题排查:类型'String'不是'int?'的子类型异常

问题场景

调用CreatePostController.getMyPostList获取帖子列表时触发未处理异常,报错栈如下:

E/flutter (12011): [错误:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常: type 'String' is not a subtype of type 'int?'
E/flutter (12011): #0      new MyPostData.fromJson (package:demandium/feature/create_post/model/my_post_model.dart:144:5)
E/flutter (12011): #1      new Content.fromJson.<anonymous closure> (package:demandium/feature/create_post/model/my_post_model.dart:62:30)
E/flutter (12011): #2      List.forEach (dart:core-patch/growable_array.dart:416:8)
E/flutter (12011): #3      new Content.fromJson (package:demandium/feature/create_post/model/my_post_model.dart:61:20)
E/flutter (12011): #4      new PostModel.fromJson (package:demandium/feature/create_post/model/my_post_model.dart:18:39)
E/flutter (12011): #5      CreatePostController.getMyPostList (package:demandium/feature/create_post/controller/create_post_controller.dart:90:29)
E/flutter (12011): <asynchronous suspension>

原因分析

从报错栈可定位到异常触发点在MyPostData.fromJson的第144行,核心问题是:后端接口返回的某个字段值为String类型,但Flutter模型类MyPostData中对应字段定义为int?类型,直接赋值时出现类型不匹配。

典型例子:后端返回的post_id字段值是"1001"(字符串格式),但模型里定义int? postId;,直接写postId = json['post_id']就会触发类型转换异常。

解决方案

方案1:修改模型的fromJson方法,添加类型转换逻辑

在MyPostData.fromJson方法中,对存在类型不匹配的字段做显式转换,用int.tryParse()处理字符串转int,同时兼容空值场景:

原错误代码示例(第144行附近):

MyPostData.fromJson(Map<String, dynamic> json) {
  // 直接赋值导致类型不匹配
  postId = json['post_id'];
  // 其他字段...
}

修改后的代码:

MyPostData.fromJson(Map<String, dynamic> json) {
  // 判断字段类型后再转换
  postId = json['post_id'] is String 
      ? int.tryParse(json['post_id']) 
      : json['post_id'] as int?;
  // 其他存在类型问题的字段同理处理
}

方案2:协调后端修复数据类型

如果后端接口该字段的预期类型为int,仅因疏忽返回了字符串格式,直接让后端调整接口,返回标准int类型值即可解决问题。

方案3:统一模型字段类型(不推荐)

若字段确实可能同时返回String或int类型,可将模型中的字段定义为dynamic,或者统一设为String类型(后续使用时再转int),但这种方式会增加类型不安全风险,需谨慎使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 14:10:22